版权声明:本文为自学而写,如有错误还望指出,谢谢^-^ https://blog.csdn.net/weixin_43871369/article/details/89606832
题目描述
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s ="catsanddog",
dict =["cat", "cats", "and", "sand", "dog"].
A solution is["cats and dog", "cat sand dog"].
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<string>res;
if(dict.find(s)!=dict.end()) res.push_back(s);
int size=s.size();
for(int i=1;i<size;++i)
{
string word=s.substr(i);
if(dict.find(word)==dict.end()) continue;
vector<string>temp=wordBreak(s.substr(0,i),dict);
Combine(temp,word);
res.insert(res.begin(),temp.begin(),temp.end());
}
return res;
}
private:
void Combine(vector<string>&tt,const string app)
{
for(auto &elem:tt)
elem+=' '+app;
return ;
}
};
拓展:字符串函数
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str="This is a just example.";
cout<<str.substr(5)<<endl;
size_t pos=str.find("just");
cout<<str.substr(pos)<<endl;
cout<<str.substr(0,3)<<endl;
return 0;
}
运行结果如下:
is a just example.
just example.
Thi
Process returned 0 (0x0) execution time : 0.068 s
Press any key to continue.
说明str.substr(n)表示从字符串str里截取从str[n]-str[str.size()-1]的元素的子串
而str.substr(m,n)表示从str[m]开始截取n个字符的子串
类似题目
题目描述
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".
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if(dict.find(s)!=dict.end()) return true;
int size=s.size();
for(int i=size-1;i>0;--i)
{
string word=s.substr(i);
if(dict.find(word)==dict.end())
continue;
if(wordBreak(s.substr(0,i),dict)) return true;
}
return false;
}
};