leetcode:t9键盘(十)

519 阅读1分钟

题目:

在老式手机上,用户通过数字键盘输入,手机将提供与这些数字相匹配的单词列表。每个数字映射到0至4个字母。给定一个数字序列,实现一个算法来返回匹配单词的列表。你会得到一张含有有效单词的列表。映射如下图所示:  

示例:

输入: num = "8733", words = ["tree", "used"]
输出: ["tree", "used"]

输入: num = "2", words = ["a", "b", "c", "d"]
输出: ["a", "b", "c"]

题解:

class Solution {
public:
    vector<string> getValidT9Words(string num, vector<string>& words) {
        vector<string> ans;
        int n=num.size(),w=words.size();
        if(n==0||w==0) return ans;
        vector<char> table={'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'};//'t'-'a'
        for(string s:words){
            if(s.size()==n){
                int i=0;
                for(;i<n;i++){
                    if(table[int(s[i]-'a')]!=num[i]) break;
                }
                if(i==n) ans.push_back(s);
            }
        }
        return ans;
    }
};

//by:wangxc-3

解析:

思路:生成table容器,容量为26,然后遍历words中的单词

这道题因为题目比较量小,所以用暴力法甚至要比其他的什么bfs等更省力省时,所以直接穷举就完事了

输入: num = "8733", words = ["tree", "used"]
输出: ["tree", "used"]

n = num.size() = 4

w= words.size() = 2

i 代表着num中的第几位

s[i]代表着word中的第i位

生成table容器的那一步比较难想,这里也用了一些c++的基础知识,vector等,table里面存放的是26个英文字母分别对应的数字,再以后的比较中如果没有对应其应该在数字序列中对应的数字,那么就会报错