Created
November 13, 2017 01:32
-
-
Save shailrshah/a8101c47c54f91c83a9e743136042df4 to your computer and use it in GitHub Desktop.
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// wordBreak("facebook", ["face", "book"]) -> true | |
public boolean wordBreak(String s, List<String> wordDict) { | |
Set<String> set = new HashSet<>(wordDict); | |
if(set.contains(s)) | |
return true; | |
Queue<Integer> queue = new LinkedList<>(); | |
Set<Integer> visited = new HashSet<>(); | |
queue.add(0); | |
visited.add(0); | |
while(queue.size() > 0) { | |
int start = queue.poll(); | |
for(int end = start+1; end <= s.length(); end++) { | |
if(visited.contains(end)) continue; | |
if(set.contains(s.substring(start, end))) { | |
if(end == s.length()) | |
return true; | |
queue.add(end); | |
visited.add(end); | |
} | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment