美文网首页
word break

word break

作者: 81bad73e9053 | 来源:发表于2017-06-09 08:20 被阅读14次
public class Solution {
    /**
     * 内存使用超过限制 
     */
   public boolean wordBreak(String s, Set<String> dict) {
            int n = s.length();
            boolean[] dp = new boolean[n + 1];
            dp[0] = true;
            for (int i = 1; i < n + 1; i++) {
                for (int j = 0; j < i; j++){
                    if(dp[j] && dict.contains(s.substring(i - j,i))) {
                        dp[i] = true;
                        break;
                    }
                }
            }
            return dp[n];
        }
    
}



public class Solution {
    private int getMaxLength(Set<String> dict) {
        int maxLength = 0;
        for (String word : dict) {
            maxLength = Math.max(maxLength, word.length());
        }
        return maxLength;
    }

    public boolean wordBreak(String s, Set<String> dict) {
        if (s == null || s.length() == 0) {
            return true;
        }

        int maxLength = getMaxLength(dict);
        boolean[] canSegment = new boolean[s.length() + 1];

        canSegment[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            canSegment[i] = false;
            for (int lastWordLength = 1;
                     lastWordLength <= maxLength && lastWordLength <= i;
                     lastWordLength++) {
                if (!canSegment[i - lastWordLength]) {
                    continue;
                }
                String word = s.substring(i - lastWordLength, i);
                if (dict.contains(word)) {
                    canSegment[i] = true;
                    break;
                }
            }
        }

        return canSegment[s.length()];
    }
} 

相关文章

网友评论

      本文标题:word break

      本文链接:https://www.haomeiwen.com/subject/glexqxtx.html