public class Solution {
/**
* @param s: A string s
* @param dict: A dictionary of words dict
*/
public boolean wordSegmentation(String s, Set<String> dict) {
// 2015-05-18 假设contains方法时间复杂度为常数,O(n^2)
if (s == null) {
return false;
}
if (s.length() == 0) {
return true;
}
int n = s.length();
int maxLen = getMaxLen(dict); //这样做是为了进一步降低时间复杂度,否则超时
boolean[] can = new boolean[n + 1]; // length is n + 1
can[0] = true;
for (int i = 1; i < n + 1; i++) {
can[i] = false;
for (int len = 1; len <= maxLen && len <= i; len++) {
// 只要有一次不满足条件,直接结束for-loop
if (can[i - len] && dict.contains(s.substring(i - len, i))) {
can[i] = true;
break;
}
}// for
}// for
return can[n];
}
// 假定dict有m个词,O(m)
private int getMaxLen(Set<String> dict) {
int maxLen = 0;
for (String word : dict) {
maxLen = Math.max(maxLen, word.length());
}
return maxLen;
}
}
[LintCode]Word Breakpublic class Solution { /** * @param s: A string s * @param dict: A dictionary of words dict */ public boolean wordSegmentation(String s, Set dict) {