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

[LeetCode] Word Break

时间:2014-07-09 00:53:55      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   数据   art   

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

 

方法一:

DFS,

start已知,当start超过str长度时,说明全部字符串都能找到了。。

小数据可过,大数据时超时

Submission Result: Time Limit Exceeded

Last executed input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
 1 class Solution {
 2     public:
 3         bool wordBreak(string s, unordered_set<string> &dict)
 4         {
 5             return wordBreak(s,0, dict);
 6         }   
 7 
 8         bool wordBreak(string s, int start, unordered_set<string> & dict)
 9         {   
10             size_t size =  s.size();
11             if(size == 0) return false;
12             if(start >= size)
13                 return true;
14 
15             for( int i = start; i <size; i++)
16             {   
17                 string str = s.substr(start, i-start+1);
18                 if(dict.find(str) != dict.end())
19                 {   
20                     if(wordBreak(s,i+1, dict))
21                        return true;
22                 }   
23 
24             }
25             return false;
26         }
27 };

 

[LeetCode] Word Break,布布扣,bubuko.com

[LeetCode] Word Break

标签:style   blog   http   color   数据   art   

原文地址:http://www.cnblogs.com/diegodu/p/3830038.html

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