<DP> (high frequency) 139

139. Word Break

Simple return results available dp, complex with dfs

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length() + 1];
        
        dp[0] = true;
        //枚举所有substring
        for(int i = 1; i <= s.length(); i++){
            for(int j = 0; j < i; j++){
                if(dp[j] && wordDict.contains(s.substring(j, i))){
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}

 

Guess you like

Origin www.cnblogs.com/Afei-1123/p/12010273.html
Recommended