T9:给定T9键盘的按键顺序,求所以可以得到的字典中的单词。
最暴力的方法是建立键盘数字到字母的映射,然后深搜,时间复杂度为O(4 ^ n),其中n为num的长度,提交了一下,超时了,所以应该提前打好表,直接返回即可。
class Solution {
private:
vector<char> KeyBoard = {
'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'
};
map<string, vector<string>> Table;
void buildTable(const vector<string> &words)
{
for(auto word : words)
{
string num;
for(auto c : word)
{
num.push_back(KeyBoard[c - 'a']);
}
Table[num].push_back(word);
}
}
public:
vector<string> getValidT9Words(string num, vector<string>& words) {
buildTable(words);
auto iter = Table.find(num);
if(iter != Table.end()) return iter->second;
else return {};
}
};
本文介绍了一种利用T9键盘输入序列快速查找字典中匹配单词的算法。通过构建数字到字母的映射,并预先生成所有可能的单词组合,实现了高效搜索。文章详细解释了算法原理,包括暴力搜索的不足与优化后的解决方案。
245

被折叠的 条评论
为什么被折叠?



