题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
//首先定义一个for负责每次比较temp和下一个的最大公共前缀,初始时,temp为数组中的第一个元素
int n = strs.size();
if(n == 0) return "";
if(n == 1) return strs[0];
string temp = strs[0];
for(int i = 1; i < strs.size(); i++){
string str = strs[i];
int k = 0;
for(int j = 0; j < temp.size() ; j++){
if(str[j]== temp[j]) k++;
else break;
}
temp = temp.substr(0, k);
}
return temp;
}
};

