1. 程式人生 > >LeetCode 211. 新增與搜尋單詞

LeetCode 211. 新增與搜尋單詞

設計一個支援以下兩種操作的資料結構:

void addWord(word)
bool search(word)

search(word) 可以搜尋文字或正則表示式字串,字串只包含字母 . 或 a-z 。 . 可以表示任何一個字母。

示例:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

說明:

你可以假設所有單詞都是由小寫字母 a-z 組成的。目前除錯時間過長class WordDictionary {
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        vector<string>  Dic ;
    }
       vector<string>  Dic ;
    /** Adds a word into the data structure. */
    void addWord(string word) {
        Dic.push_back(word) ;
       
    }
   
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    bool search(string word) {
       
        bool flag = false ;
        for(int i = 0 ;i<Dic.size();i++)
        {
            for(int j = 0;j< word.size();j++)
            {
                if(Dic[i].size() != word.size())
                {
                   
                    break;
                }
               
                if(word[j]=='.'||word[j]==Dic[i][j])
                {
                    flag = true ;
                }
                else
                {
                    flag = false ;
                   
                }
                if(flag == false)
                {
                    break ;
                }  
            }
                if(flag == true)
                {
                    break ;
                }            
        }
        if(flag)
        {
         return true ;          
        }
        else
        {
        return false ;           
        }
    }
};/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * bool param_2 = obj.search(word);
 */