有一天,小赵正在愉快的敲代码,小钱说:“小赵,你这个变量的名字取的可读性不行啊,我都不知道哪里到哪里代表什么意思。”
小赵不服气的说:“那你给我一组变量名,我保证我的变量名可以拆开,并且拆开的每一个变量名都在你这组变量名中出现”。
现在小钱提供了一组不含重复变量名的列表,你能判断小赵的变量名是否能够拆分为多个小钱提供的变量名吗,能则输出True,不能则输出False。
说明:可以重复使用小钱提供的变量名,输入变量名长度均不超过10000,变量名个数不超过10000,所有变量名总字符长度不超过106106。
输入格式
第一行输入待拆分的变量名,第二行输入多个变量名,用空格隔开。
输出格式
根据能不能拆分输出True或False。
输入样例:
thisisadog
this thisis is a dog
输出样例:
True
这里直接用unordered_set<string> 当时笔试时过了, 在acwing会超时
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <unordered_set>
using namespace std;
bool wordBreak(string s, unordered_set<string> & words) {
vector<bool> dp(s.size()+1,false);
dp[0] = true;
for(int i=1;i<=s.size();i++){
for(int j=0;j<i;j++){
if(dp[j] && words.find(s.substr(j,i-j))!=words.end()){
dp[i] = true;
break; // 找到就不用继续下去
}
}
}
return dp[s.size()];
}
int main()
{
string str1,str2,line;
unordered_set<string> words;
getline(cin,str1);
getline(cin,line);
stringstream ss(line);
while(ss>>str2) words.insert(str2);
if(wordBreak(str1, words))
cout<<"True"<<endl;
else
cout<<"False"<<endl;
}