编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
输入:vector<string>& strs
1. strs空, return "";
2. strs.size == 1 return strs[0];
3. re = "";
4. 遍历strs[0],嵌套遍历strs, 判断strs[0][i] == strs[j][i] ,不相等则return re; strs遍历结束则re = re+strs[0][i];
5. strs[0]遍历结束则return strs[0];
// Author: BJTU 张佳星
// Email: jiaxing0901@163.com
#include <iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string re = "";
if (strs.empty()) return re;
if (strs.size() == 1) return strs[0];
for (int i = 0; i < strs[0].size(); i++)
{
for (int j = 1; j < strs.size(); j++)
{
if (strs[j][i] != strs[j - 1][i])
return re;
}
re = re + string(1, strs[0][i]);
}
return re;
}
};