LeetCode() Word Search II
生活随笔
收集整理的這篇文章主要介紹了
LeetCode() Word Search II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
超時,用了tire也不行,需要再改。
class Solution {class TrieNode { public:// Initialize your data structure here.TrieNode() {for(int i=0;i<26;i++)next[i]=NULL;isString = false;}TrieNode *next[26];bool isString; };class Trie { public:Trie() {root = new TrieNode();}// Inserts a word into the trie.void insert(string word) {TrieNode* p=root;for(int i=0;i<word.size();i++){if(p->next[word[i]-'a'] == NULL)p->next[word[i]-'a']=new TrieNode();p=p->next[word[i]-'a'];}p->isString=true;}// Returns if the word is in the trie.bool search(string word) {TrieNode* p=root;for(int i=0;i<word.size();i++){if(p->next[word[i]-'a'] == NULL) return false;p=p->next[word[i]-'a'];}if(p->isString == true)return true;return false;// return p->isString;}// Returns if there is any word in the trie// that starts with the given prefix.bool startsWith(string prefix) {TrieNode* p=root;for(int i=0;i<prefix.size();i++){if(p->next[prefix[i]-'a'] == NULL) return false;p=p->next[prefix[i]-'a'];}return true;}private:TrieNode* root; };// Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key"); public:vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {vector<string> res;Trie s;for(auto i:words){if(s.search(i)){s.insert(i);res.push_back(i);}else if(exist(board,i)){res.push_back(i);s.insert(i);}}sort(res.begin(),res.end());return res;}bool exist(vector<vector<char>>& board,string word){for(int i=0;i<board.size();i++)for(int j=0;j<board[0].size();j++)if(exist(board,word,i,j,0)) return true;return false;}bool exist(vector<vector<char>>& board,string word,int x,int y,int pos){if(pos == word.size()) return true;if(x<0 || x>=board.size() || y<0 || y>=board[0].size()) return false;if(word[pos] == board[x][y]){char c=board[x][y];board[x][y]='#';bool res=exist(board,word,x+1,y,pos+1)||exist(board,word,x-1,y,pos+1)||exist(board,word,x,y+1,pos+1)||exist(board,word,x,y-1,pos+1);board[x][y]=c;return res;}return false;} };
轉載于:https://www.cnblogs.com/yanqi110/p/5011644.html
總結
以上是生活随笔為你收集整理的LeetCode() Word Search II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UIView 的基础
- 下一篇: linux工具:ssh---未完