LeetCode | Longest Common Prefix

题目:

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



思路:

首先找出所有字符串的最小长度。然后依次比较前几位在各个字符串中是否相同,若相同,则作为输出结果;否则,停止循环。


代码:

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = INT_MAX;
        for(int i = 0; i < strs.size(); i++)
        {
            if(strs[i].size() < len)
            {
                len = strs[i].size();
            }
        }
        
        if(len == INT_MAX)
        {
            len = 0;
        }
        
        bool same = true;
        int i = 0;
        for(; i < len; i++)
        {
            char c = strs[0][i];
            for(int j = 1; j < strs.size(); j++)
            {
                if(c != strs[j][i])
                {
                    same = false;
                    break;
                }
            }
            if(!same)
            {
                break;
            }
        }
        
        int num;
        if(!same)
        {
            num = i;
        }
        else
        {
            num = len;
        }
        
        string str;
        for(int k = 0; k < num; k++)
        {
            str.push_back(strs[0][k]);
        }
        return str;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11833825
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞