word break

public class Solution {
    /**
     * 内存使用超过限制 
     */
   public boolean wordBreak(String s, Set 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 dict) {
        int maxLength = 0;
        for (String word : dict) {
            maxLength = Math.max(maxLength, word.length());
        }
        return maxLength;
    }

    public boolean wordBreak(String s, Set 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)