[LeetCode] 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".

解题思路:

参考链接:http://blog.csdn.net/linhuanmars/article/details/22358863

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

 

 

 
posted @ 2016-03-30 23:10  skycore  阅读(195)  评论(0编辑  收藏  举报