leetcode--Longest Common Prefix

1.题目分析

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

2.解法分析

最近的几个leetcode都好简单,不描述了

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        string empty;
        if(strs.empty())return empty;
        if(strs.size()==1)return strs[0];
 
        string temp = strs[0];
        int i=1;
        while(i<strs.size())
        {
            int j=0;
            while(temp[j]==strs[i][j]&&j<temp.length()&&j<strs[i].length())j++;
            if(j==0)return empty;
            temp=temp.substr(0,j);
            i++;
        }
        
        return temp;
        
    }
};
原文地址:https://www.cnblogs.com/obama/p/3271525.html