cfperea
BAN USERThis is an excellent candidate for using hash tables:
A possible solutions is as follows:
int lookUp(char character)
{
unordered_map< char , char > map;
map['a'] = 2;
map['b'] = 2;
map['c'] = 2;
...
map['x'] = 9;
map['y'] = 9;
map['z'] = 9;
map['A'] = 2;
map['B'] = 2;
map['C'] = 2;
...
map['X'] = 9;
map['Y'] = 9;
map['Z'] = 9;
// Makes sure the character key is in the hash map
assert(map.find(character) != map.end());
return map[character];
}
void printPhoneNumber(string alphaNumber)
{
for (int i = 0; i < alphaNumber.size(); ++i)
{
char currentCharacter = alphaNumber.at(i);
if (isdigit(currentCharacter))
cout << currentCharacter;
else if (currentCharacter == '-')
continue;
else
{
int digit = lookUp(currentCharacter);
cout << digit;
}
}
cout << endl;
}
int main()
{
string alphaNumber = "1-800-COM-CAST";
printPhoneNumber(alphaNumber); // Valid phone number
string alphaNumber2 = "1-800-C??-CAST";
printPhoneNumber(alphaNumber2); // Throws an Assertion error
return 0;
}
Aside from the normal case " a ", you also need to check for the boundary cases which include when the "a" is in the beginning of the string, the only letter in the string and at the end. This is a possible solution:
#include <iostream>
#include <string>
using namespace std;
int numWords(const string & word)
{
int result = 0;
if (word.at(0) == 'a' && word.size() == 1)
return 1;
for (int i = 0; i < word.size() - 1; ++i)
{
if (i == 0 && word.at(i) == 'a' && word.at(i + 1) == ' ')
++result;
else if (i == word.size() - 2 && word.at(i) == ' ' && word.at(i + 1) == 'a')
++result;
else if (word.at(i) == ' ' && word.at(i + 1) == 'a' && word.at(i + 2) == ' ')
++result;
}
return result;
}
int main()
{
string word = "a How are you this is a test of a possible input a";
cout << numWords(word) << endl;
return 0;
}
The output in this case is 4
- cfperea June 13, 2013
This problem can be solved with a stack-based approach. I have tested the following code and it works.
- cfperea August 12, 2013