Add and Search Word - leetcode 221号题目个人题解
题目要求
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z
or .
. A .
means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
解题思路
这是一道Medium难度的题
题目要我们建立一个数据结构,称为WordDictionary,它有两个功能。
要能够实现能向其中添加词语
能够进行查找。输入一个词语,其中的任何字母可以用
.
符号来代替,如果在WordDictionary中有这个词语的话,就返回true
,否则返回false
。
那么,由此看来这个问题主要应该是一个字符串模式匹配的问题。
首先,我们可以建立一个元素为字符串的向量来存储单词。
然后,每次新增添一个单词,就把它push到这个向量里。
最后,只要写一个字符串匹配的函数,用来搜索字符串就好了。当然,按照题目的要求,这个匹配函数要把目标单词中的.
都当成是匹配的。
详细代码
按照这个思路,很快便可以把代码写出来了:
#include<vector>
#include<string>
using namespace std;
bool scomp(string main,string temp){
if(main.length()!=temp.length()) return false;
for(int i = 0;i<(int)temp.length();i++){
if(temp[i]!=main[i]&&temp[i]!='.')
return false;
}
return true;
}
class WordDictionary {
private:
vector<string> cont;
public:
void addWord(string word) {
cont.push_back(word);
}
bool search(string word) {
int num = (int)cont.size();
for(int i = 0;i<num;i++){
if(scomp(cont[i],word)) return true;
}
return false;
}
};
调试之后,进行提交,跑过了几个测试,就出现问题了。
超时了!!
在跑最后一个测试样例的时候,要进行非常多次查询,进行线性搜索的话非常耗时间!本来想,可以建立一个字典树,这样应该可以减少查询的时间可是碍于.
符号的存在,无法建立字典树。这就非常尴尬了。
思路改进
那么还有什么办法可以减少查询时间呢?稍加思考,我们不难发现,就算用.
号来取代单词中的任何字母,单词的总长度是不变的。那么我们在存储单词的时候,把同样长度的单词放在一起,查询的时候只在同样长度的单词里面查找,不就更快了嘛!
说走咱就走,把储存单词用的向量改成向量组vector<string> cont[3000];
。把长度为 i 的单词存在cont[i]
中,每次查找在对应向量里面查找就ok了。
详细代码如下:
#include<vector>
#include<string>
using namespace std;
bool scomp(string main,string temp){
if(main.length()!=temp.length()) return false;
for(int i = 0;i<(int)temp.length();i++){
if(temp[i]!=main[i]&&temp[i]!='.')
return false;
}
return true;
}
class WordDictionary {
private:
vector<string> cont[3000];
public:
void addWord(string word) {
int len = (int)word.length();
cont[len].push_back(word);
}
bool search(string word) {
int len = (int)word.length();
int num = (int)cont[len].size();
for(int i = 0;i<num;i++){
if(scomp(cont[len][i],word)) return true;
}
return false;
}
};
这一次,不仅顺利通过测试,还超过了所有本题的提交者。想想用这么简单的办法实现了这效率,心里还有点小激动。
结语
有的时候,简单的办法,也可以是好办法。
(完)