【LeetCode】9.Array and String — Longest Common Prefix 最长共同前缀

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

If there is no common prefix, return an empty string "".

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.

存储string类型的向量一定程度上可以看成二维数组。 最重要的思想是按照最小长度的字符串作为最外层遍历循环。

class Solution {
public:
string longestCommonPrefix(vector<string>& strs)
{
    //首先,找到所有字符串中最短的那一个.
    int min=0;
    for (int i = 0; i < strs.size(); i++)
    {
        if (min < strs[i].size()) min = strs[i].size();
    }
    if (min == 0) return "" ;
    //然后根据最短的那个字符串进行遍历
    string result="" ;
    int counter = 0;//计数器
    for (int i = 0; i < min; i++)
    {
        char compare = strs[0][i];
        for (int j = 0; j < strs.size(); j++)
        {
            if (strs[j][i] == compare) {
                continue;
            }
            else return result;
        }
        result.push_back(compare);
    }
    return result;
}
};

猜你喜欢

转载自www.cnblogs.com/hu-19941213/p/10970807.html
今日推荐