LeetCode–T9鍵盤
博客說明
文章所涉及的資料來自互聯網整理和個人總結,意在於個人學習和經驗匯總,如有什么地方侵權,請聯系本人刪除,謝謝!
說明
題目
在老式手機上,用戶通過數字鍵盤輸入,手機將提供與這些數字相匹配的單詞列表。每個數字映射到0至4個字母。給定一個數字序列,實現一個算法來返回匹配單詞的列表。你會得到一張含有有效單詞的列表。映射如下圖所示:
示例 1:
輸入: num = "8733", words = ["tree", "used"]
輸出: ["tree", "used"]
示例 2:
輸入: num = "2", words = ["a", "b", "c", "d"]
輸出: ["a", "b", "c"]
提示:
num.length <= 1000
words.length <= 500
words[i].length == num.length
num中不會出現 0, 1 這兩個數字
Java
思路
將26個字母按順序將對應的數字存入數組,再比對輸入的數字是否符合
代碼
class Solution {
public List<String> getValidT9Words(String num, String[] words) {
List<String> res = new ArrayList<>();
char[] map = {'2','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','7','7','7','8','8','8','9','9','9','9'};
for(String word : words){
int index = 0;
boolean flag = true;
for(char c : word.toCharArray()){
char n = map[c-'a'];
if(n != num.charAt(index++)){
flag = false;
break;
}
}
if(flag){
res.add(word);
}
}
return res;
}
}
感謝
leetcode
以及勤勞的自己
關注公眾號: 歸子莫,獲取更多的資料,還有更長的學習計划