题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param strs string字符串vector
* @return string字符串
*/
string longestCommonPrefix(vector<string>& strs) {
// write code here
string res = "";
if(strs.size() == 0){
return res;
}
bool isEqual = true;
string temp = strs[0];
int index = 0;
int temp_len = temp.length();
for( int i = i; i < strs.size(); i++ ){
temp = strs[i];
if(temp_len > temp.length()){
temp_len = temp.length();
index = i;
}
}
temp = strs[index];
string compare_str = "";
for(int len = 1; len <= temp_len ; len++){
compare_str = temp.substr(0,len);
for(int i = 0; i < strs.size(); i++){
if(compare_str.compare(strs[i].substr(0,len)) != 0){
isEqual = false;
break;
}
}
if(!isEqual){
break;
}else{
res = compare_str;
}
}
return res;
}
};

基恩士成长空间 451人发布