码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode - Word Break

时间:2014-09-22 12:40:12      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   os   ar   for   sp   cti   on   

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(std::string s, std::unordered_set<std::string> &dict) {
        int n = (int)s.size();
		std::vector<int> dp(n+1,0);
		dp[0] = 1;
		for(int i = 1; i <= n; i++)
		{
			if(dp[i-1])
			{
				int index = i - 1;
				for(int j = index; j < n; j++)
				{
					std::string str = s.substr(index,j-index+1);
					if(dict.count(str) > 0)
						dp[j+1] = true;
				}
			}
		}
		return dp[n];
    }
};


leetcode - Word Break

标签:style   color   io   os   ar   for   sp   cti   on   

原文地址:http://blog.csdn.net/akibatakuya/article/details/39459587

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!