word-break

Given a string s and a dictionary of words dict, determine if s 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 WordBreak
{
    //切割字符串
    public static boolean wordBreak1(String s, Set<String> dict)
    {
        int _len = s.length();
        
        for(int i = 0; i < _len; ++i)
        {
            if(i == 0)
            {
                if(dict.contains(s.substring(0, _len)))
                    return true;
            }
            else
            {
                if (dict.contains(s.substring(0, i)) && dict.contains(s.substring(i, _len)))
                    return true;
            }
                
        }
        
        return false;
    }
    
    //動態規劃
    //狀態轉移方程 f(n) = f(m) && c(m + 1, n)
    //f(n)表示前n個字符是否可分,c(m + 1, n)表示字典中是否包含第m+1到第n個字符的字符串
    public static boolean wordBreak2(String s, Set<String> dict)
    {
        int _len = s.length();
        boolean[] _arrays = new boolean[_len + 1];
        _arrays[0] = true;
        
        for(int i = 1; i <= _len; ++i)//i對應方程中的n
        {
            for(int j = 0; j < i; ++j)//j對應方程中的m
            {
                if(_arrays[j] && dict.contains(s.substring(j, i)))
                {
                    _arrays[i] = true;
                }
            }
        }
        
        return _arrays[_len];
    }

}

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