本文共 1735 字,大约阅读时间需要 5 分钟。
原文链接:
给定一个字符串s和一个单词字典,确定是否可以将s分割为一个或多个字典单词的空格分隔的序列。
例如:For example, givens = "leetcode",dict = ["leet", "code"].
因为"leetcode"可以分割为"leet code", 所以返回true.
public class Solution { public boolean wordBreak(String s, Setdict) { return wordBreakHelper(s, dict, 0); } public boolean wordBreakHelper(String s, Set dict, int start){ if(start == s.length()) return true; for(String a: dict){ int len = a.length(); int end = start+len; //end index should be <= string length if(end > s.length()) continue; if(s.substring(start, start+len).equals(a)) if(wordBreakHelper(s, dict, start+len)) return true; } return false; }}
时间是O(n ^ 2)和超过了时间限制。
定义一个数组t[],这样t[i]= =true => 0-(i- 1)可以使用字典进行分段初始状态t[0]= = true
public class Solution { public boolean wordBreak(String s, Setdict) { boolean[] t = new boolean[s.length()+1]; t[0] = true; //set first to be true, why? //Because we need initial state for(int i=0; i s.length()) continue; if(t[end]) continue; if(s.substring(i, end).equals(a)){ t[end] = true; } } } return t[s.length()]; }}
时间:O(字符串长度*字典大小)。
public boolean wordBreak(String s, SetwordDict) { int[] pos = new int[s.length()+1]; Arrays.fill(pos, -1); pos[0]=0; for(int i=0; i
转载地址:http://autrl.baihongyu.com/