Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created January 15, 2019 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/7c1a90dd2b40606ecd499beea4df3921 to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/7c1a90dd2b40606ecd499beea4df3921 to your computer and use it in GitHub Desktop.
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
if(wordDict.empty()) return false;
unordered_set<string> dict(wordDict.begin(), wordDict.end());
unordered_set<int> visited;
queue<int> q({0}); //Queue initialization should include container
while(!q.empty()){
int next = q.front();
q.pop();
if(visited.count(next)!=0) continue;
visited.insert(next);
string tempS = "";
for(int i = next; i < s.size(); i++){
if(dict.count(tempS += s[i]) != 0){
q.push(i+1);
if(i+1 == s.size()) return true;
}
}
}
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment