LeetCode 第140题
要注意,用一个maxLen来表示每次递归遍历的最长的长度。这个maxLen为数组中最长的字符串长度与要遍历的字符串的长度的较小值。这样能避免额外的遍历。
时间复杂度O(n^2),两个for循环来扫字符串
class Solution {
int maxLen = 0;
List<String> resList = new ArrayList<String>();
public List<String> wordBreak(String s, List<String> wordDict) {
for(int i = 0; i < wordDict.size(); i++) {
if(wordDict.get(i).length() > maxLen) {
maxLen = wordDict.get(i).length();
}
}
maxLen = Math.min(maxLen, s.length());
StringBuilder sb = null;
for(int i = 1; i < maxLen+1; i++) {
sb = new StringBuilder();
String substring = s.substring(0, i);
if(wordDict.contains(substring)) {
sb.append(substring).append(" ");
fun(s, wordDict, i, sb);
}
}
return resList;
}
public void fun(String str, List<String> list, int index, StringBuilder sb) {
if(index >= str.length()) {
sb.delete(sb.length()-1, sb.length());
resList.add(sb.toString());
sb.append(" ");
return;
}
for(int i = 1; i < maxLen+1 && index+i <= str.length(); i++) {
String subStr = str.substring(index, index+i);
if(list.contains(subStr)) {
sb.append(subStr).append(" ");
fun(str, list, index+i, sb);
sb.delete(sb.length()-subStr.length()-1, sb.length());
}
}
}
}