zoukankan      html  css  js  c++  java
  • LeetCode题解(14)--Longest Common Prefix

    https://leetcode.com/problems/longest-common-prefix/

    原题:

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

    思路:

    简单,直接遍历查找即可。

    AC代码:

     1 class Solution {
     2 public:
     3     string longestCommonPrefix(vector<string>& strs) {
     4         int n=strs.size();
     5         if (n==1)
     6             return strs[0];
     7         if (n==0)
     8             return "";
     9         int k=strs[0].size();
    10         bool flag=true;
    11         string res="";
    12         for(int i=0;i<n;i++)
    13             k=(k<strs[i].size())? k:strs[i].size();
    14         for(int t=0;t<k;t++){
    15             for(int i=0;i<n;i++){
    16                 if(strs[i][t]!=strs[0][t]){
    17                     flag=false;
    18                     break;
    19                 }
    20             }
    21             if (flag==true)
    22                 res.push_back(strs[0][t]);
    23             else 
    24                 break;
    25         }
    26         return res;
    27     }
    28 };
  • 相关阅读:
    Github地址
    第三次冲刺12.16
    第三次冲刺12.07~12.15
    第二次冲刺11.24~12.03
    第十天
    照片
    最终总结
    app的推广
    第三个Sprint冲刺事后诸葛亮报告
    第三个Sprint团队贡献分
  • 原文地址:https://www.cnblogs.com/aezero/p/4549689.html
Copyright © 2011-2022 走看看