17. Letter Combinations of a Phone Number

Description:

https://leetcode.com/problems/letter-combinations-of-a-phone-number/#/description

Boundary:

No

Algorithm:

Nothing special.

Code:

class Solution {
public:
vector<string> letterCombinations(string digits) {
string mapping[10] = { ” “,””,”abc”,”def”,”ghi”,”jkl”,”mno”,”pqrs”,”tuv”,”wxyz” };
vector<string> result1, result2;

for (int i = 0; i < digits.size();i++)
{
int idx = (int)(digits[i]) – 48;
if (idx == 1) continue;
for (int j = 0; j < mapping[idx].size(); j++)
{
if (result1.size() > 0)
for (int k = 0; k < result1.size(); k++)
{
string tmp = “”;
tmp += result1[k] + mapping[idx].substr(j, 1);
result2.push_back(tmp);
}
else
result2.push_back(mapping[idx].substr(j, 1));
}

result1 = result2;
result2.clear();
}
return result1;
}
};

Leave a Reply

Your email address will not be published. Required fields are marked *