码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-06-03 23:48:55      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:let   not   lse   leetcode   letters   example   efi   counter   span   

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;
}
};

 

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

标签:let   not   lse   leetcode   letters   example   efi   counter   span   

原文地址:https://www.cnblogs.com/hu-19941213/p/10970807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!