題目
編寫一個函數來查找字符串數組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 “”。
示例 1:
輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:
輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共前綴。
說明:
所有輸入只包含小寫字母 a-z 。
#cpp
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int n = strs.size();
if(n == 0) return "";
if(n == 1) return strs[0];
sort(strs.begin(),strs.end());
for(int i = 0;i < min(strs[0].length(),strs[n-1].length());i++){
if(strs[0][i] != strs[n-1][i])
return strs[0].substr(0,i);
}
return strs[0];
}
};
補充知識點
c++ vertor sort
先從第一個字符比較,然後比較第二個,一次類推,和字符長度基本無關
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector <string> words = {"the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle"};
sort(words.begin(), words.end());
for (vector<string>::iterator it = words.begin(); it != words.end(); it++){
cout << *it << endl;
}
return 0;
}
輸出
/Users/zhangjiabin/Documents/cpp/cpp/yufa/vectorStringSort/cmake-build-debug/vectorStringSort
fox
jumps
over
quick
red
red
slow
the
the
turtle
Process finished with exit code 0