编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
思路:循环遍历字符串,逐位进行判断;首先将strs[0]设置为结果字符串res,然后遍历字符串数组对res进行更新,如果有公共前缀则返回最长(遇到不同位采取slice或者substr切片,并且直接跳出内层循环),这里面如果没有公共部分,则默认切片为空,res = “”。
!!!slice和substr函数使用的时候,其中语法为substr(start, end),start为起始坐标,end为结束坐标,字符串结束坐标不是最后一个字母,而是通常为最后一个字母后面的空字符,切记切记
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string res = strs[0];
for (int i = 1; i < strs.size(); i++){
for (int j = 0; j < res.size(); j++){
if (res[j] != strs[i][j]){
res = res.substr(0, j);
break;
}
}
}
return res;
}
};
int main(){
Solution s;
vector<string> strs = {"flower","flow","flight"};
cout << s.longestCommonPrefix(strs) << endl;
return 0;
}