菱纱梦

导航

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

 

算法:在网上查到的,动态规划算法

 1 class Solution {
 2 public:
 3     bool wordBreak(string s, unordered_set<string> &dict) {
 4         int len=s.size();
 5         bool *k=new bool[s.size()];
 6         memset(k,false,s.size());
 7         for(int i=0;i<len;i++)
 8         {
 9             k[i]=dict.find(s.substr(0,i+1))!=dict.end()?true:false;
10             if(k[i])  continue;
11             for(int j=0;j<i;j++)
12             {
13                 if(k[j])
14                 {
15                     k[i]=dict.find(s.substr(j+1,i-j))!=dict.end()?true:false;
16                     if(k[i])  break;
17                 }
18             }
19         }
20         return k[len-1];
21     }
22 };

 

posted on 2014-10-04 09:54  菱纱梦  阅读(181)  评论(0编辑  收藏  举报