第一题真的没想到……
1 int findLUSlength(string a, string b) { 2 if (a == b) 3 return -1; 4 else if (a.length() > b.length()) 5 return a.length(); 6 else 7 return b.length(); 8 }
第二题真的想不出来,神仙题……
1 int findLUSlength(vector<string>& strs) { 2 int size = strs.size(); 3 if (size == 0) 4 return 0; 5 else if (size == 1) 6 return strs[0].size(); 7 else 8 { 9 map<int, map<string, int>> mp; 10 for (int i = 0; i < strs.size(); ++i) 11 { 12 mp[strs[i].size()][strs[i]] += 1; 13 } 14 auto it = mp.end(); 15 --it; 16 vector<string> behind; 17 18 while (mp.size() > 0) 19 { 20 for (auto &e : it->second) //it->second:是当前那个key对应的所有map<string,int>的集合 21 if (e.second == 1) //只出现过1次 22 { 23 bool found = true; 24 for (int j = 0; j < behind.size(); ++j) //j:处理过的string索引 25 { 26 int m = 0; 27 for (int k = 0; k < behind[j].size() && m < e.first.size(); ++k) //k:处理过的string单个字符的索引,m:当前那个 28 { 29 if (behind[j][k] == e.first[m]) 30 { 31 ++m; 32 } 33 } 34 if (m == e.first.size()) 35 { 36 found = false; 37 break; 38 } 39 } 40 if (found == true) 41 return it->first; 42 } 43 for (auto &e : it->second) 44 behind.push_back(e.first); 45 it = mp.erase(it); 46 if (mp.size() > 0) 47 --it; 48 } 49 } 50 return -1; 51 }
在看了该题的题解后,冥思苦想出为什么这么写以后,依旧报错vector下标出错,许久没找出来错误,在网上一搜这个bug,转载自别人的博客。
https://blog.csdn.net/zhulinzhulinlin/article/details/79363735 以后循环条件再不敢随便的写。
接下来说说代码的思路。用了一个嵌套的map,一次遍历以后,长度大的势必排在后面。但又要找长度大的,所以用尾迭代器。第一次时behind中一个没有,此时若找到一个只出现过一次的长度较长的,直接成立。若出现过不只一次的,那个放入behind中,如此反复