leetcode.524
為什么這個把dictionary按照長度從大到小且相同長度按照字典序排序的sort沒有作用?
而在本地vscode運行輸出是正確的”abc“
static bool cmp1(string& a, string& b){
return a.size() > b.size();
}
static bool cmp2(string a, string b){
return a.compare(b) == -1;
}
string findLongestWord(string s, vector<string>& dictionary) {
sort(dictionary.begin(), dictionary.end(), cmp1);
int i, j, size = dictionary.size();
for(i = j = 0; j < size; i = ++j){
while( j < size - 1 && dictionary[j + 1].size() == dictionary[i].size()) j++;
sort(dictionary.begin() + i, dictionary.begin() + j + 1, cmp2);
}
}
輸入 s = "abce" ,dictionary = ["abe","abc", "asd"] 我在leetcode編譯器上的輸出為abe
uj5u.com熱心網友回復:
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include <iostream>
using namespace std;
static bool cmp1(string& a, string& b){
bool r;
r=(a.size() > b.size());
if (!r) {
if (a.size() == b.size()) {
r=(a.compare(b) < 0);
return r;
}
}
return r;
}
string findLongestWord(string s, vector<string>& dictionary) {
sort(dictionary.begin(), dictionary.end(), cmp1);
for (int i=0;i<dictionary.size();i++) {
cout<<dictionary[i]<<endl;
}
return s;
}
int main() {
string s="abce";
vector<string> dictionary;
dictionary.push_back("abe");
dictionary.push_back("abc");
dictionary.push_back("asd");
string t=findLongestWord(s,dictionary);
return 0;
}
//abc
//abe
//asd
//
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/267887.html
標籤:新手樂園
