首页 > 代码库 > 【leetcode】14. longest common prefix

【leetcode】14. 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;

    }
};
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

【leetcode】14. longest common prefix