首页 > 代码库 > leetcode Longest Common Prefix

leetcode Longest Common Prefix

找出单词的最长公共前缀

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        int len=strs.size();
        if(len==0)
            return "";
        int length=strs[0].size(),j;
        for(int i=1;i<len;i++)
        {
            for(j=0;j<strs[i].size();j++)
            {
                if(j>=length||strs[i][j]!=strs[0][j])
                    break;
            }
            length=j;//length记录当前的最长公共前缀长度
        }
        return strs[0].substr(0,length);
    }
};