天天看點

程式員面試金典 - 面試題 16.20. T9鍵盤(數組)

1. 題目

在老式手機上,使用者通過數字鍵盤輸入,手機将提供與這些數字相比對的單詞清單。

每個數字映射到0至4個字母。給定一個數字序列,實作一個算法來傳回比對單詞的清單。

你會得到一張含有有效單詞的清單。映射如下圖所示:

程式員面試金典 - 面試題 16.20. T9鍵盤(數組)
示例 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 這兩個數字           

複制

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/t9-lcci

著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

2. 解題

類似題目:LeetCode 17. 電話号碼的字母組合(回溯)

class Solution {
public:
    vector<string> getValidT9Words(string num, vector<string>& words) {
        string key[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        vector<string> ans;
        int i;
        bool ok;
        for(auto& w : words)
        {
        	ok = true;
        	for(i = 0; i < w.size(); ++i)
        	{
        		if(key[num[i]-'0'].find(w[i]) == string::npos)
        		{
        			ok = false;
        			break;
        		}
        	}
        	if(ok)
        		ans.push_back(w);
        }
        return ans;
    }
};           

複制

36 ms 12.2 MB

  • 或者比較數字是否相等
class Solution {
public:
    vector<string> getValidT9Words(string num, vector<string>& words) {
        char ch[26] = {'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'};
        vector<string> ans;
        int i;
        bool ok;
        for(auto& w : words)
        {
        	ok = true;
        	for(i = 0; i < w.size(); ++i)
        	{
        		if(num[i] != ch[w[i]-'a'])
        		{
        			ok = false;
        			break;
        		}
        	}
        	if(ok)
        		ans.push_back(w);
        }
        return ans;
    }
};           

複制

28 ms 12 MB