zoukankan      html  css  js  c++  java
  • [LeetCode] Longest Common Prefix

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

    模拟法,先选取第一个字符串,之后依次和后面的字符串得出LCP

     1 class Solution {
     2 public:
     3     string longestCommonPrefix(vector<string> &strs) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if (strs.size() == 0)
     7             return "";
     8             
     9         string s = strs[0];
    10         
    11         for(int i = 1; i < strs.size(); i++)
    12         {
    13             int j = 0;
    14             
    15             int len = min(strs[i].size(), s.size());
    16             
    17             while(j < len)
    18             {
    19                 if (strs[i][j] != s[j])
    20                     break;
    21                 j++;
    22             }
    23             
    24             s.erase(j, s.size());
    25         }
    26         
    27         return s;
    28     }
    29 };
  • 相关阅读:
    单词统计
    团队项目介绍--“益青春APP”
    团队项目 NABCD介绍
    兰猪耳
    薄雪万年草
    佛甲草
    针叶天蓝绣球
    白芨
    萱草
    吉祥草
  • 原文地址:https://www.cnblogs.com/chkkch/p/2766466.html
Copyright © 2011-2022 走看看