Leetcode 14 Longest Common Prefix

来源:互联网 发布:中国电信德国数据漫游 编辑:程序博客网 时间:2024/06/05 02:40

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

以最短的字符串为limit,n方遍历所有字符串,虽然很暴力,但应该是最优解

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        string result;        int limit=INT_MAX;        for(int i=0;i<strs.size();i++)        {            int len=strs[i].length();            limit=min(INT_MAX,len);        }        if(limit==INT_MAX) return "";        for(int i=0;i<limit;i++)        {            for(int j=0;j<strs.size();j++)                if(strs[j][i]!=strs[0][i])                    return result;            result+=strs[0][i];        }           return result;    }};


0 0