larscheng / algo

0 stars 0 forks source link

【Check 72】2024-05-13 - 139. 单词拆分 #178

Open larscheng opened 6 months ago

larscheng commented 6 months ago

139. 单词拆分

larscheng commented 6 months ago

思路

代码


class Solution {

    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> wordDictSet = new HashSet<>(wordDict);
        boolean[] dp = new boolean[s.length()+1];
        dp[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i ; j++) {
                if (dp[j] && wordDictSet.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}

复杂度