题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param strs string字符串vector
* @return string字符串
*/
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()){return "";}
string cur = strs[0]; //暂存第一个元素
string ret ;
int max = cur.size(); // "公共"所以第一个的大小也决定了公共前缀的大小
//遍历每个字符串
//记录最大的相等的个数
for(auto e:strs)
{
int count = 0;
for(size_t i =0;i<e.size()&& i<max; i++)
{
if(e[i] == cur[i])
{
++count;
}
}
max = count;
}
//记录完最大的大小
for(size_t i = 0; i<max;i++)
{
ret += cur[i];
}
return ret;
// write code here
}
};
求数组里最长的公共前缀,因为是公共前缀,所以只要所给的字符串数组不为空,就可以从第一个字符串入手。
第一个字符串也决定了公共前缀的大小,所以只要记录第一个字符串,然后遍历剩下的字符串,依次比较,记录相等元素的最大值即可。
#C++面试题#
查看9道真题和解析