Word Break I,II

Given a string s and a dictionary of words dict, determine ifs can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

 

public class Solution {

    // http://needjobasap.blogspot.com/2014/11/word-break-leetcode.html

    //http://fisherlei.blogspot.com/2013/11/leetcode-word-break-solution.html

    public boolean wordBreak(String s, Set<String> dict) {

        

        boolean[] dp = new boolean[s.length()+1];

        dp[0] = true;

        

      //  for(int i=0;i<s.length();i++){

      for(int i=1;i<=s.length();i++){

            for(int j=0; j< i; j++){

                if(dp[j] && dict.contains(s.substring(j,i))) {

                    dp[i]=true;

                    break;

                }

            }

        }

        return dp[s.length()];

        

    }

}

 

II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

就是在1 的基础上加了个dfs的应用

public class Solution {

    public ArrayList<String>  wordBreak(String s, Set<String> wordDict) {

        ArrayList<String> res = new ArrayList<String>();

        if(s==null||s.length()==0) return res;

        int len = s.length();

        boolean [] dp = new boolean[len+1];

        dp[0] = true;

        for(int i=1;i<=len;i++){

            for(int j=0;j<i;j++){

                String tmp = s.substring(j,i);

                if(dp[j] && wordDict.contains(tmp)){

                    dp[i] = true;

                    break;

                }

            }

        }

        if(dp[len]==false) return res;

        StringBuilder item  = new StringBuilder();

        dfs(s, 0, item, res, wordDict);

        return res;

    }

    private void dfs(String s, int start, StringBuilder item, ArrayList<String> res, Set<String> dict){

        int len = s.length();

        if(start>=len){

            res.add(new String(item));

            return;

        }

        for(int i=start+1;i<=len;i++){

            String sub = s.substring(start,i);

            if(dict.contains(sub)){

                int ol = item.length();

                if(ol!=0){

                    item.append(" ");

                }

                item.append(sub);

                dfs(s,i,item,res,dict);

                item.delete(ol,item.length());

            }

        }

    }

}

 

你可能感兴趣的:(break)