Leetcode 139.单词拆分

OJ链接 :139.单词拆分 

44483c4fde364e059c51e690f7e69e12.png

代码:

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> set = new HashSet<String>(wordDict);
            int n = s.length();
            boolean[] dp = new boolean[n+1];
            dp[0] = true;//初始化 保证后边正常
            s = " " + s; //映射

            for(int i =1;i<=n; i++){
                for(int j =1;j<=i;j++){
                    if( dp[j-1]==true && set.contains(s.substring(j,i+1))){
                        dp[i]=true;
                        break;
                    }
                }


            }
            return dp[n];
    }
}