[LeetCode Practice] [Intermediate] 139. Word Split

[LeetCode Practice] [Intermediate] 139. Word Split

139. Word Split

139. Word Split

Algorithm idea: dp

topic:

Insert picture description here
Transition matrix: dp[i]=dp[j] && check(s[j…i−1])

java code

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

Guess you like

Origin blog.csdn.net/qq_39457586/article/details/115057628