Leetcode—139. Word Break

来源:互联网 发布:微信淘宝群怎么做到的 编辑:程序博客网 时间:2024/06/07 17:39

问题描述:

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

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

将一个给定的字符串是否可以完全按照字典dict内的元素分解。

解题思路:

两种思路:

考虑可达性的概念,第一种方法是从前向后遍历字符串s,然后计算以当前字符s[ i ] 作为字符子串的首元素,是否在字典Dict中。具体做法为依次寻找当前位置s[ i ]之后的字符s[ j ], j>i,检验子串s[i……j]是否存在于dict中如果存在我们就说 j 位置是可达点这样一直遍历到最后。如果最后一位为可达点,则返回true。

另一种也是遍历字符串s,但是这一次我们把当前字符s[ i ]作为字符子串的尾元素,即判断 i 之前的所有可达点是和 i 组成字符串,是否在dict内存在,只要有一个存在,就是可达的

第一种方法比第二种方法效率要低一些,如果我们使用一些简化技巧,比如只有当前位置可达,才开始寻找之后可达点,如果 j 位置的不可达,才进行可达性检验。两种方法的效率应该是差不多的。

下面给出第二种方法的代码:

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






原创粉丝点击