LeetCode---17.电话号码的字母组合
程序员文章站
2022-06-05 16:39:05
...
题目来源:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/
题目描述:
代码如下:
class Solution {
public List<String> letterCombinations(String digits) {
LinkedList<String> list = new LinkedList<>();
if (digits.equals("")) {
return list;
}
list.add("");
String[] strs = new String[] { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
for (int i = 0; i < digits.length(); i++) {
//将输入字符串的每个字符转换成对应输入的数字
int num = Integer.parseInt(String.valueOf(digits.charAt(i)));
//while中的条件为了找出list中没有追加新字符的字符串,因为追加字符后的字符串会重新放入list,不判断将会无限循环
while (list.peek().length() == i) {
//将尚未追加字符的字符串取出
String str = list.pop();
for (char c : strs[num].toCharArray()) {
//将取出的字符串追加字符后重新放入list
list.offer(str + c);
}
}
}
return list;
}
}
上一篇: 再来个随机字符串