题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param strs string字符串vector
* @return string字符串
*/
bool static cmp(string s1, string s2){ // 按照长度对str排序
return s1.size()<s2.size();
}
string longestCommonPrefix(vector<string>& strs) {
// write code here
string result = "";
if(strs.size() == 0) return result;
sort(strs.begin(), strs.end(), cmp);
for(int i = 0; i< strs[0].size(); i++){ // strs[0]为长度最短的string,
char c = strs[0][i];
for(string s : strs){ //依次比较对应字符是否相等
if(s[i] != c){
return result;
}
}
result += c;
}
return result;
}
};
