https://blog.csdn.net/mine_song/article/details/72081998
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
- 拆分时可以重复使用字典中的单词。
- 你可以假设字典中没有重复的单词。
-
class Solution { public boolean wordBreak(String s, List<String> wordDict) { if(s==null){ return true; } if(wordDict==null){ return false; } int len=s.length(); boolean[] dp=new boolean[len+1];//表示dp[i]以i-1结尾是否存在字典中的 dp[0]=true; for(int i=0;i<=len;i++){//substring左闭右开等于也无妨 for(int j=0;j<i;j++){ if(dp[j]&&wordDict.contains(s.substring(j,i))){ dp[i]=true; break; } } } return dp[len]; } }
BFS
-
public boolean wordBreak(String s, List<String> dict) { if (dict.contains(s)) return true; Queue<Integer> queue = new LinkedList<Integer>(); queue.offer(0); //使用set去检查去除重复计算 //这是是时间复杂度降到O(N^2)的关键 Set<Integer> visited = new HashSet<Integer>(); visited.add(0); while (!queue.isEmpty()) { int curIdx = queue.poll(); for (int i = curIdx + 1; i <= s.length(); i++) { if (visited.contains(i)) continue; if (dict.contains(s.substring(curIdx, i))) { //如果到达中重点, //注意此时的i是curIdx + 1 if (i == s.length()) return true; queue.offer(i); visited.add(i); } } } return false; }