Word Break
来源:互联网 发布:sugarnms网管软件 编辑:程序博客网 时间:2024/05/21 08:45
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"
.
//使用DP算法!
//注:f(i) = f(j) && find(s.substr(j , i-j)); // f(i)表示s[0..i]可以分词! ---理解即可 一个for 针对i,一个针对j!!
class Solution {public: //注:f(i) = f(j) && find(s.substr(j , i-j)); // f(i)表示s[0..i]可以分词! bool wordBreak(string s, unordered_set<string> &dict) { int length = s.size(); bool table[length+1]; if(s.empty() || dict.empty())return false; memset(table,false,sizeof(bool)*(length+1)); table[0] = true; for(int i = 1; i <= length ; i++) { for(int j = 0; j < i; j++) { //substr(j , i-j) 此处的j为长度的意思,而下标从0开始,故而不用加1! if(table[j] && dict.find(s.substr(j , i-j)) != dict.end()) { table[i] = true ; } } } return table[length]; } };
增加输出最多可以划分的个数,时间复杂度O(N^2*m^2*size),也可采取划分,再在trie树中找,时间复杂度O(N^2*m+size*m)//查找速度快!(在搜索中trie树。)
#include <iostream> #include <vector>#include <cstdlib> #include <algorithm>#include <string>using namespace std; //注:f(i) = f(j) && find(s.substr(j , i-j)); // f(i)表示s[0..i]可以分词! int wordBreak(string s, vector<string> &dict) { int length = s.size(); int *table = new int[length+1]; if(s.empty() || dict.empty())return false; memset(table,0,sizeof(int)*(length+1)); table[0] = 1; for(int i = 1; i <= length ; i++) { for(int j = 0; j < i; j++) { //substr(j , i-j) 此处的j为长度的意思,而下标从0开始,故而不用加1! if(table[j]>0 && find(dict.begin(),dict.end(),s.substr(j , i-j)) != dict.end()) { table[i] = table[j]+1; } } } return table[length] > 1?table[length]-1:0;//一开始多加了1} int main(){string str[8] = {"a", "an","ave","na","ve","bar", "nave", "on"};vector<string> dict(str,str+8);string my_str("anavebaron");int res;if(res = wordBreak(my_str,dict))cout<<"find:"<<res<<endl;elsecout<<" not find"<<endl;return 0;}
0 0
- Word-break:break-word
- Word Break && Word Break ||
- word-break
- Word Break
- Word Break
- Word Break
- word break
- Word Break
- Word Break
- Word Break
- Word Break
- Word Break
- Word Break
- Word Break
- Word Break
- Word Break
- Word Break
- Word Break
- C++闭包: Lambda Functions in C++11
- J-Link V8和openOCD结合调试程序
- 拼装json字符串
- ExecutorService线程池
- qcw——qt自定义控件
- Word Break
- IE6 PNG图片
- 位图详解
- web app Native app
- Objective-C最糟糕的13件事
- IPCS资源
- CocoaPods一个Objective-C第三方库的管理利器
- window.onload与$(document).ready()区别
- 你终将成为你潜意识中想要成为的人