题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 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