|
|
感觉写的比较笨。。
- #include <iostream>
- #include <vector>
- #include <map>
- using namespace std;
- vector<vector<string>> res;
- vector<string> candidate{""};
- map<int, vector<string>> wordmap;
- bool isContain(string a, string b){
- if(b==""){
- return true;
- }
- for(unsigned int i=0;i<a.size();i++){
- string newa = a;
- newa.erase(newa.begin()+i);
- if(newa==b){
- return true;
- }
- }
- return false;
- }
- void help( map<int, vector<string>> &wordmap, int startlength, vector<vector<string>> &res,vector<string> &candidate){
- if(wordmap.find(startlength)==wordmap.end()){
- res.push_back(candidate);
- return;
- }
- for(unsigned int i=0;i<wordmap[startlength].size();i++){
- if(isContain(wordmap[startlength][i],candidate.back())){
- candidate.push_back(wordmap[startlength][i]);
- help(wordmap,startlength+1,res,candidate);
- candidate.pop_back();
- }
- }
- }
- string longestlist(vector<string> words){
- //find the map of word length
- for(unsigned int i=0;i<words.size();i++){
- wordmap[words[i].size()].push_back(words[i]);
- }
- help(wordmap,1,res,candidate);
- int longestindex=0;
- int longestlength=0;
- for(unsigned int i=0;i<res.size();i++){
- if(res[i].back().size()>longestlength){
- longestindex=i;
- longestlength = res[i].back().size();
- }
- }
- return res[longestindex].back();
- }
- int main ()
- {
- vector<string> words{"a","ac","abdet","afc","abrdet","ab","abd","abde"};
- string res = longestlist(words);
- return 0;
- }
复制代码 |
|