地址:https://leetcode.com/problems/letter-combinations-of-a-phone-number/
题目:
Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: “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.
理解:
用一个队列来存前面产生的字符串。遇到一个新的数字,就给前面的每个字符串都加上新数字对应的所有字母,然后依次添加到队尾。麻烦的是最后要把队列中的元素依次添加到vector中。
实现:
class Solution {
vector<string> table = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
public:
vector<string> letterCombinations(string digits) {
if (digits.empty()) return{};
queue<string> q;
q.push("");
for (char c : digits) {
int i = q.size();
while (i > 0) {
--i;
string tmp = q.front();
q.pop();
for (auto cc : table[c - '0'])
q.push(tmp + cc);
}
}
vector<string> res(q.size());
int i = 0;
while (!q.empty()) {
res[i++] = q.front();
q.pop();
}
return res;
}
};