golang刷leetcode 字符串(5)添加與搜索單詞 - 數據結構設計

設計一個支持如下兩種操做的數據結構:javascript


void addWord(word)php

bool search(word)java

search(word) 能夠搜索文字或正則表達式字符串,字符串只包含字母 . 或 a-z 。. 能夠表示任何一個字母。golang


示例:正則表達式



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


說明:算法


你能夠假設全部單詞都是由小寫字母 a-z 組成的。微信

解題思路數據結構

1,把加入的單詞保存在字典樹中架構

2,插入時,app

A,非通配符,在對應孩子節點插入

B,遇到.'對每一個子樹遞歸插入


3查找時,

A,在字典樹中逐層匹配字符。

B,非通配符 '.' 在對應子樹匹配剩下的字符。

C,遇到'.'對每一個子樹遞歸匹配,尋找一個匹配的子樹。


注意事項

1,用isWord表示是否葉子節點

2,插入的時候對於每一個孩子節點要判斷下是否已經插入



type WordDictionary struct { isWord bool childern [26]*WordDictionary}

/** Initialize your data structure here. */func Constructor() WordDictionary { return WordDictionary{ }}

/** Adds a word into the data structure. */func (this *WordDictionary) AddWord(word string) { if word==""{ return } if word[0]=='.'{ for i:=0;i<26;i++{ var t *WordDictionary if this.childern[i]==nil{ t=&WordDictionary{} this.childern[i]=t }else{ t=this.childern[i] }
if len(word)==1{ t.isWord=true }else{ t.AddWord(word[1:]) }
} return }
var t *WordDictionary if this.childern[word[0]-'a']==nil{ t=&WordDictionary{} this.childern[word[0]-'a']=t }else{ t=this.childern[word[0]-'a'] } if len(word)==1{ t.isWord=true fmt.Println(*this.childern[word[0]-'a']) return } t.AddWord(word[1:]) return}

/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */func (this *WordDictionary) Search(word string) bool { if word==""{ return false } if len(word)==1{ if word[0]=='.'{ for i:=0;i<26;i++{ if this.childern[i]!=nil && this.childern[i].isWord{ return true } } return false } fmt.Println(word) return this.childern[word[0]-'a']!=nil && this.childern[word[0]-'a'].isWord } if word[0]=='.'{ for i:=0;i<26;i++{ if this.childern[i]!=nil && this.childern[i].Search(word[1:]){ return true } } return false }
t:=this.childern[word[0]-'a'] if t==nil{ return false } return t.Search(word[1:])}

/** * Your WordDictionary object will be instantiated and called as such: * obj := Constructor(); * obj.AddWord(word); * param_2 := obj.Search(word); */


本文分享自微信公衆號 - golang算法架構leetcode技術php(golangLeetcode)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索