最长的前缀

题目:

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z 。

思路:

可以想象成二维数组,定义两个指针j 遍历字符 i遍历字符串

对每个字符串中的字符进行比较 相同就输出,反之返回空字符串

代码:

class Solution{

public:

      string longestCommonPrefix(vector<string>& strs){

           if(strs.empty()) return " ";

           strings res = " ";

           for(int j = 0; j < strs[0].size(); ++j){

                char c = strs[0][j];

                for(int i = 1; i < strs.size(); ++i){

                        if(j >= strs[i].size() || strs[i][j] != c){

                             return res;

}

}

res.push_back(c);

}

return res;

}

};

猜你喜欢

转载自blog.csdn.net/WWEVA64/article/details/85931541
今日推荐