139. Word Break
作者:互联网
My BFS Solution
public boolean wordBreak(String s, List<String> wordDict) { if(wordDict.contains(s)) return true; Queue<String> queue = new LinkedList<>(); for(String word:wordDict){ if(s.startsWith(word)){ queue.add(word); } } while(!queue.isEmpty()){ int size = queue.size(); for(int i=0;i<size;i++){ String tempS = queue.poll(); String subS = s.substring(tempS.length()); if(wordDict.contains(subS)) return true; else { for(String word:wordDict){ if(subS.startsWith(word)){ queue.offer(tempS+word); } } } } } return false; }
My Backtracking Solution:
public boolean wordBreak(String s, List<String> wordDict) { Set<String> wordSet = new HashSet<>(); for(String word: wordDict){ wordSet.add(word); } return helper(s, wordSet); } private boolean helper(String s, Set<String> set){ if(s.length()==0) return true; for(String word: set){ if(s.startsWith(word)){ if(helper(s.substring(word.length()), set)) return true; } } return false; }
以上两个Solution虽然是对的,但是对于下面的test case都TLE
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
标签:queue,set,word,String,Break,Word,wordDict,return,139 来源: https://www.cnblogs.com/feiflytech/p/15690934.html