LeetCode-Word Break

原创 2015年07月06日 17:18:52

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”.
题意:查询一个字符串是由给定字典中的单词组成。
DP解法:
对于s中(0,i)之间的字符:
1.若t=s.substr(0,i)在字典中,则dp[i]=true;
2.若t=s.substr(0,i)不在字典中
则对(0,i)之间的dp[ j ]( j > =1 && j < i )=1,则对t1=s.substr(j,i-j)判断是否在字典中,若在字典中则dp[i]=true;

 bool wordBreak(string s, unordered_set<string>& wordDict)
  {

        int n=s.length();
        if(n==0)
        {
            return false;
        }
        vector<bool> bp(n+1,false);
        for(int i=1;i<=n;++i)
        {
            string t=s.substr(0,i);
            bp[i]=wordDict.find(t)!=wordDict.end()?true:false;
            if(bp[i])
            {
                continue;
            }
            else
            {
                for(int j=1;j<i;++j)
                {
                    if(bp[j])
                    {
                         string t1=s.substr(j,i-j);
                         bp[i]=wordDict.find(t1)!=wordDict.end()?true:false;
                         if(bp[i])
                         {
                             break;
                         }
                    }

                }
            }
        }


        return bp[n];
 }
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode: Word Break II [140]

【题目】 Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where...

算法学习之回溯法(leetcode 140. Word Break II)

leetcode 140. Word Break II Given a string s and a dictionary of words dict, add spaces in s to con...

[Leetcode] Word Break II (Java)

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

leetcode:word break II

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

[LeetCode]139.Word Break

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa...

leetcode——Word Break

题目: Given a string s and a dictionary of words dict, determine if s can be segmented into a spa...

LeetCode | Word Break

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa...

Leetcode--Word Break II

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...
  • yskyj
  • yskyj
  • 2014-10-06 11:19
  • 299

word break II--LeetCode

public ArrayList wordBreak(String s, Set dict) { ArrayList res = new ArrayList(); ...

[LeetCode]Word Break II

题目描述 解题思路
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)