1. 程式人生 > >[leetcode]139. Word Break

[leetcode]139. Word Break

solution 1: 自己寫的遞迴,tle了

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        if(s.length()==0||s==null)return true;
        
        String spre="";
        String spos="";

        for(String sub:wordDict){
            
                if(s.indexOf(sub)!=-1){
                    spre=s.substring(0,s.indexOf(sub));
                    spos=s.substring(s.indexOf(sub)+sub.length());
                    // System.out.println(spre);
                    // System.out.println(spos);
                    if(wordBreak(spre,wordDict)&&wordBreak(spos,wordDict)){
                        return true;
                    }
                    
            
                }
                
            
        }
        return false; 
    }
}

Solution 2: dp

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int len = s.length();
        boolean[] dp = new boolean[len];
        
        for (int i = 0; i < len; i++) {
            for (String word : wordDict) {
                if (word.length() <= i + 1 && s.substring(i - word.length() + 1, i + 1).equals(word)) {
                    int index = i - word.length();
                    if (index == -1)  {
                        dp[i] =  true;
                    } else {
                        dp[i] = dp[index];
                    }
                    
                    if(dp[i]) break;
                }
            }
        }
        
        return dp[len - 1];
    }
}