LeetCode-14:Longest Common Prefix(最长公共前缀)

题目:

Write a function to find the longest common prefix string amongst an array of strings.

例子:

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:
* All given inputs are in lowercase letters a-z.

问题解析:

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

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

思路标签

直接比较

解答:

直接比较

  • 建立数组保存字符数组中每个字符串的长度,以最小的字符长度作为外层循环来进行判断。
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string str;
        if(strs.empty())
            return str;
        str="";
        vector<int> len;
        for(int i=0;i<strs.size();i++)
        {
            len.push_back(strs[i].size());
        }
        auto minloc=min_element(len.begin(),len.end());
        int minlen=*minloc;
        for(int j=0;j<minlen;j++)
        {
            for(int i=0;i<strs.size()-1;i++)
            {
                if(strs[i][j]!=strs[i+1][j])
                {
                    return str;
                }
            }
            str+=strs[0][j];
        }
        return str;
    }
};

猜你喜欢

转载自blog.csdn.net/Koala_Tree/article/details/81352851