题目描述:
Write a function to find the longest common prefix string amongst an array of strings.
分析:
题意:给定一些字符串,求它们的最长公共前缀。
思路:先求得所有字符串的最短长度min_length,那么它将是公共前缀可能的最长长度,我们分别获得min_length→1长度的某个字符串的前缀,如果其它字符串相同长度的前缀跟它相等,那么已经找到最长公共前缀,返回即可。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int n = strs.size();
// Exceptional Case:
if(n == 0){
return "";
}
if(n == 1){
return strs[0];
}
int min_len = INT_MAX;
for(string str: strs){
min_len = min(min_len, (int)(str.length()));
}
for(int i = min_len; i >= 1; i--){
string prefix = strs[0].substr(0, i);
bool flag = false;
for(int j = 1; j <= n - 1; j++){
if(strs[j].substr(0, i) != prefix){
flag = true;
break;
}
}
if(!flag){
return prefix;
}
}
return "";
}
};