My java solution


  • 0
    G

    My dp array contains positions that can successfully cut the string.

    public class Solution {
        public boolean wordBreak(String s, Set<String> dict) {
            int n = s.length();
            int[] dp = new int[n + 1];
            dp[0] = 0;
            
            for (int i = 1; i <= n; i++) {
                boolean f = false;
            
                for (int j = i - 1; j >= 0; j--) {
                    if (dict.contains( s.substring(dp[j], i) )) {
                        f = true;
                        break;
                    }
                    
                    if (dp[j] == 0) break;
                    j = dp[j];
                }
                
                if (f) dp[i] = i;
                else dp[i] = dp[i - 1];
            }
            return dp[n] == n ? true : false;
        }
    }

Log in to reply
 

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