Word Break

来源:互联网 发布:微盘源码搭建 编辑:程序博客网 时间:2024/06/11 23:05

Word Break

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.

Subscribe to see which companies asked this question.

解题技巧:

对于该问题,采用动态规划的方法求解,用数组isBreak表示第i个位置能否分割,那么状态转移方程有:

isBreak[i] = isBreak[j] && s. substr(j, i-j)在单词表中存在 其中,0<= j < i

代码:

#include <iostream>#include <string>#include <vector>#include <algorithm>using namespace std;//利用动态规划求解bool wordBreak(string s, vector<string>& wordDict){    int len = s.size();    sort(wordDict.begin(), wordDict.end());    vector<bool> isBreak(len+1, false);    isBreak[0] = true;    int flag = 0;    for(int i = 1; i <= len; i ++)    {        for(int j = i - 1; j >= 0; j --)        {            flag = 0;            if(isBreak[j])            {                string tmp = s.substr(j, i-j);                vector<string>::iterator it = wordDict.begin();                while(it != wordDict.end())                {                    if(*it == tmp)                    {                        isBreak[i] = true;                        flag = 1;                        break;                    }                    else if(*it > tmp) break;                    it ++;                }            }            if(flag == 1) break;        }    }    return isBreak[len];}int main(){    string s, word;    vector<string> wordDict;    cin >> s;    while(cin >> word)        wordDict.push_back(word);    cout<<wordBreak(s, wordDict);}


0 0
原创粉丝点击