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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
给出一个字符串,代表数字按键顺序,求出所有可能的字母按键顺序。这里使用队列来实现。具体实现见代码:
代码:
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.empty() || digits == "") return res;
queue<string> q;
q.push("");
for(int i = 0; i < digits.size(); ++i) {
string chars = getChars(digits[i]);
int qs = q.size();
for(int j = 0; j < qs; ++j) {
string s = q.front();
q.pop();
for(auto c:chars) {
q.push(s+c);
}
}
}
while(!q.empty()) {
res.push_back(q.front());
q.pop();
}
return res;
}
private:
string getChars(char d) {
vector<string> map{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
return map[d-'0'];
}
};