您的位置:首页 > 编程语言 > C语言/C++

17. Letter Combinations of a Phone Number LeetCode题解

2017-05-22 11:40 357 查看
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.

Subscribe to see which companies asked this question.

题意:

给定一个数字字符串,返回其数字串代表的所有可能字母组合;

数字和字符的映射关系如图所示;

题解:

2代表abd,3代表def,23则代表abc和def的所有组合,即如样例所示;

思路上可以使用递归或者循环,这里推荐写循环,因为面试官往往不喜欢递归;

Code【Java】

public class Solution {
public List<String> letterCombinations(String digits) {
if (digits.length() < 1) {
return new LinkedList<String>();
}
String mapping[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
LinkedList<String> ans = new LinkedList<String>(Arrays.asList(""));
for (int i = 0; i < digits.length(); ++i) {
int num = digits.charAt(i) - '0';
while (ans.peek().length() == i) {
String cur = ans.poll();
for (int j = 0; j < mapping[num].length(); ++j) {
ans.add(cur + mapping[num].charAt(j));
}
}
}
return ans;
}
}

Code【C++】

class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.size() < 1) {
return vector<string>();
}
string mapping[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
queue<string> ans;
ans.push("");
for (int i = 0; i < digits.size(); ++i) {
int num = digits[i] - '0';
while (ans.front().size() == i) {
string cur = ans.front();
for (int j = 0; j < mapping[num].size(); ++j) {
ans.push(cur + mapping[num][j]);
}
ans.pop();
}
}
vector<string> ret;
while (!ans.empty()) {
ret.push_back(ans.front());
ans.pop();
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Java C++ string 刷题