• 78. Longest Common Prefix【medium】


    Given k strings, find the longest common prefix (LCP).

    Example

    For strings "ABCD""ABEF" and "ACEF", the LCP is "A"

    For strings "ABCDEFG""ABCEFG" and "ABCEFA", the LCP is "ABC"

    解法一:

     1 class Solution {
     2 public:    
     3     /**
     4      * @param strs: A list of strings
     5      * @return: The longest common prefix
     6      */
     7     int min(int a, int b) {
     8         return ((a < b) ? a : b);
     9     }
    10      
    11     int calCount(string & a, string & b) {
    12         int la = a.size();
    13         int lb = b.size();
    14         int count = 0;
    15         
    16         for (int i = 0; i < la && i < lb; ++i) {
    17             if (a[i] == b[i]) {
    18                 count++;
    19             } else {
    20                 return count;
    21             }
    22         }
    23     }
    24      
    25     string longestCommonPrefix(vector<string> &strs) {
    26         int count = INT_MAX;
    27         int size = strs.size();
    28         
    29         if (size == 0) {
    30             return "";
    31         }
    32         
    33         for (int i = 0; i < strs.size() - 1; ++i) {
    34             count = min(calCount(strs[i], strs[i + 1]), count);
    35         }
    36         
    37         return strs[0].substr(0, count);
    38     }
    39 };

    解法二:

     1 class Solution {
     2 public:    
     3     /**
     4      * @param strs: A list of strings
     5      * @return: The longest common prefix
     6      */
     7     string longestCommonPrefix(vector<string> &strs) {
     8         if (strs.size() == 0) {
     9             return "";
    10         }
    11         
    12         string prefix = "";
    13         for (int i = 0; i < strs[0].length(); i++) {
    14             for (int j = 1; j < strs.size(); j++) {
    15                 if (strs[j][i] != strs[0][i]) {
    16                     return prefix;
    17                 }
    18             }
    19             prefix += strs[0][i];
    20         }
    21         
    22         return prefix;
    23     }
    24 };

     

  • 相关阅读:
    Eclipse与Tomcat
    乱入Spring+Mybatis
    windows一次无线网卡被关闭事件
    数列的考查角度收集整理2[三轮总结]
    数列的考查角度收集整理1[三轮总结]
    求函数的解析式
    不等式证明的那些事
    高中数学中最值素材整理【待编辑】
    函数与导数中常用的函数和不等关系
    坐标系与参数方程的考向整理[三轮总结]
  • 原文地址:https://www.cnblogs.com/abc-begin/p/8413817.html
Copyright © 2020-2023  润新知