LeetCode Word Break II

原題鏈接在這裏:https://leetcode.com/problems/word-break-ii/

本題是Word Break的進階題,要返回所有wordbreak的結果。

本題參照了這篇帖子:http://www.cnblogs.com/springfor/p/3877056.html

首先更具isWordBreak判斷是否能拆,若能拆看從頭到尾走,找到了一個wordDict裏包含的字符串,然後從後一個點就用遞歸方法調用helper, 遞歸的stop condition是能走到正好結尾,否則跳出for loop, res不變。

Note:  helper的for loop中若wordDict包含當前sb.toString(), 應該建立一個新的string, newString, 它相當於一個copy, 因爲回朔到這點時,str應該回到最開始的時候,若不用這個copy當回到這點時str可能已經不是最開始的狀態。

AC  Java:

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
        List<String> res = new ArrayList<String>();
        if(s == null || s.length() == 0){
            return res;
        }
        if(isWordBreak(s,wordDict)){
            helper(s, wordDict, 0, "",res);
        }
        return res;
    }
    private void helper(String s, Set<String> wordDict,int start, String str, List<String> res){
        if(start == s.length()){
            res.add(str);
            return;
        }
        
        StringBuilder sb = new StringBuilder();
        for(int i = start; i< s.length(); i++){
            sb.append(s.charAt(i));
            if(wordDict.contains(sb.toString())){
                String newString = new String();    //error
                if(str.length() == 0){
                    newString = sb.toString();
                }else{
                    newString = str + " " + sb.toString();
                }
                helper(s,wordDict,i+1,newString,res);
            }
        }
    }
    private boolean isWordBreak(String s, Set<String> wordDict){
        if(s == null || s.length() ==0){
            return true;
        }
        boolean [] dp = new boolean[s.length()+1]; 
        dp[0] = true;
        for(int i = 0; i < s.length(); i++){
            StringBuilder sb= new StringBuilder(s.substring(0,i+1));
            for(int j = 0; j<=i; j++){
                if(dp[j] && wordDict.contains(sb.toString())){
                    dp[i+1] = true;
                    break;
                }
                sb.deleteCharAt(0);
            }
        }
        return dp[s.length()];
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章