判断字符串是否能分割成字典中的单词(二)——Leetcode系列(十二)

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"].


My Answer:

public class Solution {
    private Map> map = new HashMap>();
    public List wordBreak(String s, Set dict) {
        Set sentences = toSentence(s, dict);
        return setToList(sentences);
    }
    
    private Set toSentence(String s, Set dict){
        if(! map.containsKey(s)){
            Set temp = new HashSet();
            map.put(s,temp);
        }else{
        	return map.get(s);
        }
        int length = s.length();
        Set mySet = map.get(s);
        if(dict.contains(s)){
            mySet.add(s);
        }
        for(int i = 1; i < length; i++){
            String head = s.substring(0,i);
            if(!dict.contains(head)){
                continue;
            }
            Set tail = null;
            if(! map.containsKey(s.substring(i))){
                tail = toSentence(s.substring(i),dict);
            }else{
                tail = map.get(s.substring(i));
            }
            if(tail.size() == 0){
            	continue;
            }

            Iterator tailIte = tail.iterator();
            while(tailIte.hasNext()){
            	mySet.add(head + " " + tailIte.next());
            }
            
        }
        
        return mySet;
        
    }
    
    private List setToList(Set set){
        List list = new ArrayList();
        Iterator ite = set.iterator();
        while(ite.hasNext()){
            list.add(ite.next());
        }
        return list;
    }
}
题目来源:https://oj.leetcode.com/problems/word-break-ii/

你可能感兴趣的:(java,LeetCode)