LeetCode:139.Word Break

来源:互联网 发布:男朋友礼物 知乎 编辑:程序博客网 时间:2024/06/05 09:54

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

  • Total Accepted: 132579
  • Total Submissions: 460844
  • Difficulty: Medium
  • Contributors: Admin

题目的意思是,已给一个字符串数组dict,与一个字符串s,查看s是否能由数组dict中的一个或多个字符串组成。

一开始最快想到的是递归,代码如下:

class Solution {public:bool wordBreak(string s, vector<string>& wordDict) {if (s.size() == 0)return true;if (wordDict.size() == 0)return false;for (int i = 0;i < s.size();i++){if (find(wordDict.begin(), wordDict.end(), s.substr(0, i + 1)) != wordDict.end()){if (wordBreak(s.substr(i + 1, s.size() -1- i), wordDict))return true;}}return false;}};


果然超时了。

一般递归超时的题目会想到动态规划的方法,的确这题字符串的每个状态都是以前面的有关的,例子:

s = "leetcode",
dict = ["leet", "code"]

倒着想,如果检测到字符c,如果在c之前的“leet”能够在数组里面成功表示,且c也是可以在数组中找到,那么“leetc”是满足条件的,只要满足一种情况即可。代码:

class Solution { public:bool wordBreak(string s, vector<string> &wordDict) {    if (s.size()!=0 && wordDict.size()== 0)    return false;    bool *record = new bool[s.size()+1];    for (int i = 0;i<s.size()+1;i++)        record[i] = false;    record[0] = true;    for (int i = 1; i < s.size() + 1; i++) {        for (int j = i - 1; j >= 0; j--) {            if (record[j] && find(wordDict.begin(),wordDict.end(),s.substr(j, i - j)) != wordDict.end()) {                record[i] = true;                break; //只要能满足一种情况即可            }        }    }    return record[s.size()];    }};

34 / 34 test cases passed.
Status: 

Accepted

Runtime: 3 ms

0 0
原创粉丝点击