leetcode14. longest common prefix

Posted clnchanpin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode14. longest common prefix相关的知识,希望对你有一定的参考价值。

@requires_authorization
@author johnsondu
@create_time 2015.7.13 10:11
@url [longest-common-prefix](https://leetcode.com/problems/longest-common-prefix/)
/**
 * 求出string中的最小长度
 * 然后依次每一个string从第一个開始进行比較
 * 时间复杂度:O(n*m), n是string个数,m是string的长度
 */
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int len = strs.size();
        if(len == 0) return "";
        if(len == 1) return strs[0];
        int mins = 0xffffff;
        for(int i = 0; i < len; i ++){
            if(mins > strs[i].size()) mins = strs[i].size();
        }
        int idx = -1;
        for(int j = 0; j < mins; j ++){
            char ch = strs[0][j];
            bool flag = false;
            for(int i = 1; i < len; i ++){
                if(ch != strs[i][j]){
                    flag = true;
                    break;
                }
            }
            if(flag) break;
            idx ++;
        }
        if(idx == -1) return "";
        string ans = "";
        for(int i = 0; i <= idx; i ++)
            ans += strs[0][i];
        return ans;

    }
};

以上是关于leetcode14. longest common prefix的主要内容,如果未能解决你的问题,请参考以下文章

leetcode14. longest common prefix

Leetcode 14. Longest Common Prefix

Leetcode 14 Longest Common Prefix

Leetcode14. Longest Common Prefix

LeetCode 14: Longest Common Prefix

leetcode 14. Longest Common Prefix