首页 > 其他 > 详细

LeetCode139:Word Break

时间:2014-04-18 12:27:21      阅读:682      评论:0      收藏:0      [点我收藏+]

题目:

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题,说实话,本人也是算法方面的菜鸟一枚,关于DP方面的题,还不太会解,没办法,只能多练习了。

这里采用DP中的自底向上实现,dp[i]表示前i个字符能否进行Wordbreak。当求解dp[i]时,可利用已经求解的dp[i-1],

dp[i-2]…dp[1],dp[0]进行求解。

对于dp[n]的求解,我们可以将n个字符进行切分求解,分为前i个字符和后n-i个字符,i可以为(0,1,2,3,4…n-1)

假设i为1时,可根据dp[i]和后面的n-1个字符组成的单词是否在dict中来判断dp[n],只要i(0,1,2,3,4…n-1)其中一种

情况为真,则dp[n]为true,表示可以进行workbreak。

实现代码:

bubuko.com,布布扣
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;

/*
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".
*/ 
class Solution {
public:
    bool wordBreak(string s, unordered_set<string> &dict) {
        if(s.size() == 0 || dict.size() == 0)
            return false;
        int len = s.size();
        vector<bool> dp(len+1, false);//保存状态,dp[i]表示前i个字符是否可以进行wordBread 
        dp[0] = true;
        for(int i = 1; i <= len; i++)
            for(int j = 0; j < i; j++)
            {
                if(dp[j] && dict.count(s.substr(j, i-j)) == 1)//对前i个字符进行切分时,只要有一种情况为true,则dp[i]=true 
                {
                    dp[i] = true;
                    break;
                }
            }
        return dp[len];
        
    }
    
    bool wordBreak2(string s, unordered_set<string> &dict) {
        if(s.size() == 0 || dict.size() == 0)
            return false;
        int len = s.size();
        vector<bool> dp(len+1, false);//保存状态,dp[i]表示前i个字符是否可以进行wordBread 
        dp[0] = true;
        for(int i = 0; i < len; i++)
            if(dp[i])
            {
                for(int j = 1; j <= len-i; j++)
                    if(dict.count(s.substr(i, j)) == 1)
                        dp[i+j] = true;
            }

        return dp[len];
        
    }
    

};

int main(void)
{
    string s("leetcode");
    unordered_set<string> dict;
    dict.insert("leet");
    dict.insert("code");
    Solution solution;
    bool ret = solution.wordBreak(s, dict);
    cout<<ret<<endl;

    return 0;
}
bubuko.com,布布扣

LeetCode139:Word Break,布布扣,bubuko.com

LeetCode139:Word Break

原文:http://www.cnblogs.com/mickole/p/3672108.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!