Question: 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”].
Solution:
class Solution {public: vector<string> letterCombinations(string digits) { vector<string> res; int len = digits.size(); if(len <= 0) return res; int first = 0; while(digits[first] <'2' || digits[first] > '9') first++; int num = (digits[first] - '2') * 3; if(digits[first] <= '7'){ stringstream ss; string s; ss<<(char)('a'+num); ss>>s; res.push_back(s); ss.clear(); ss<<(char)('b'+num); ss>>s; res.push_back(s); ss.clear(); ss<<(char)('c'+num); ss>>s; res.push_back(s); } if(digits[first] == '7'){ res.push_back("s"); } else if(digits[first] == '8'){ res.push_back("t"); res.push_back("u"); res.push_back("v"); } else if(digits[first] == '9'){ res.push_back("w"); res.push_back("x"); res.push_back("y"); res.push_back("z"); } for(int i = 1 ; i < len ;i++){ if(digits[i] < '2' || digits[i] > '9') continue; int num = (digits[i] - '2') * 3; string tmp = res.front(); int nowlen = tmp.size(); while(tmp.size() == nowlen){ res.erase(res.begin()); if(digits[i] <= '7'){ res.push_back(tmp+(char)(97 + num)); res.push_back(tmp+(char)(98 + num)); res.push_back(tmp+(char)(99 + num)); } if(digits[i] == '7'){ res.push_back(tmp+"s"); } else if(digits[i] == '8'){ res.push_back(tmp+"t"); res.push_back(tmp+"u"); res.push_back(tmp+"v"); } else if(digits[i] == '9'){ res.push_back(tmp+"w"); res.push_back(tmp+"x"); res.push_back(tmp+"y"); res.push_back(tmp+"z"); } tmp = res.front(); } } return res; }};Attention:
methods of char to string:“”+ char //wrong char+ “”//wrong stringstream ss;string s;//right stringstream ss;ss.str()//wrong 2. from key ‘7’ ,it make changes. not ‘9’ 3. vector has’t function of pop_front(), but list have.
新闻热点
疑难解答