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);
}