leetcode13题解

2025-10-13

leetcode13

描述

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: strs = [“flower”,”flow”,”flight”] Output: “fl” Example 2:

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

思路

超级大模拟,直接写就行,没啥可说的。

代码

class Solution {
public:
    inline int mymax(int a,int b){
        return a>b?a:b;
    }
    string longestCommonPrefix(const vector<string>& strs) {
        string res="";
        char cur;
        int m_lenth=0;
        for(const auto &s:strs){
            m_lenth=mymax(m_lenth,s.length());
        }
        res.reserve(m_lenth);
        for(int i=0;i<m_lenth;i++){
            for(int j=0;j<strs.size();j++){
                if(!j&&i){
                    res.push_back(cur);
                }
                if(strs[j].size()<=i){
                    
                    return res;
                }
                else{

                    if(!j){
                        cur=strs[j][i];
                    }
                    else{
                        if(cur!=strs[j][i]){
                            return res;
                        }
                    }
                }
            }
        }
        res.push_back(cur);
        return res;
        
    }
};