- Letter Combinations of a Phone Number My Submissions QuestionEditorial Solution
Total Accepted: 78554 Total Submissions: 273286 Difficulty: Medium
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
Submission Details
25 / 25 test cases passed.
Status: Accepted
Runtime: 0 ms
思路:依次迭代,比较简单
class Solution {
public:
vector<string> letterCombinations(string digits) {
int n = digits.size();
vector<string> res;
map<char,string> nmap;
init_map(nmap);
for(int i=0;i<n;++i){
if(digits[i]=='1')continue;//1代表空,无效数字越过
string word= nmap[digits[i]];
vector<string> sw,stmp;
for(int j=0;j<word.size();++j){
vector<char> vs;
vs.push_back(word[j]);
vs.push_back('\0'); //特别注意char* 转string
sw.push_back(vs.data());
for(int k=0;k<res.size();++k)
stmp.push_back(res[k]+sw[j]);
}
if(res.size()==0)res = sw;
else res = stmp;
}
return res;
}
void init_map(map<char,string> &nmap)
{
nmap['1']="";nmap['2']="abc";nmap['3']="def";
nmap['4']="ghi";nmap['5']="jkl";nmap['6']="mno";
nmap['7']="pqrs";nmap['8']="tuv";nmap['9']="wxyz";
nmap['0']=" ";
}
};