[leetcode] 14. Longest Common Prefix 解题报告

题目链接:https://leetcode.com/problems/longest-common-prefix/

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


思路:每次子串长度加1,直到子串不相等即是最大公共前缀

代码如下:

class Solution {
public:
    string longestCommonPrefix(vector& strs) {
        if(strs.size()==0) return "";
        string ans;
        for(int i = 0; i < strs[0].size(); i++)
        {
            char c = strs[0][i];
            for(auto ch: strs)
                if(i == ch.size()||ch[i]!=c) return ans;
            ans += c;
        }
        return ans;
    }
};


你可能感兴趣的:(leetcode,string)