Java Solution no Fancy


  • 3
    public class Solution {
        public boolean wordBreak(String s, List<String> wordDict) {
            int n = s.length();
            int maxLen = 0;
            int minLen = Integer.MAX_VALUE;
            for (String word : wordDict) {
                minLen = Math.min(minLen, word.length());
                maxLen = Math.max(maxLen, word.length());
            }
            boolean[] dp = new boolean[n + 1];
            dp[0] = true;
            for (int i = 0; i < n; i++) {
                for (int len = minLen; len <= maxLen; len++) {
                    if (i + len > n) break;
                    String curr = s.substring(i, i + len);
                    if (wordDict.contains(curr) && dp[i]) {
                        dp[i + len] = true;
                    }
                    if (dp[n]) return true;
                }
            }
            return dp[n];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.