zoukankan      html  css  js  c++  java
  • LeetCode OJ:Longest Common Prefix(最长公共前缀)

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

    求很多string的公共前缀,用个两重循环就可以,代码如下:

     1 class Solution {
     2 public:
     3     string longestCommonPrefix(vector<string>& strs) {
     4         string prefix;
     5         if(strs.size() == 0 || strs[0].size() == 0)
     6             return "";
     7         int start = 0;
     8         bool endLoop = false;
     9         char cmp = strs[0][0];
    10         while(true && !endLoop){
    11             cout << cmp << endl;
    12             for(int i = 0; i < strs.size(); ++i){
    13                 if(start >= strs[i].size() || cmp != strs[i][start]){
    14                     endLoop = true;
    15                     break;
    16                 }
    17             }    
    18             if(!endLoop){
    19                 start++;
    20                 if(start < strs[0].size())
    21                     cmp = strs[0][start];
    22             }
    23 
    24         }
    25         return strs[0].substr(0, start - 1);
    26     }
    27 };
  • 相关阅读:
    单位根反演学习笔记
    省选模拟测试17
    省选模拟测试16
    省选模拟测试15
    省选模拟测试14
    省选模拟测试13
    P4491 [HAOI2018]染色
    省选模拟测试12
    P4389 付公主的背包
    洛谷P3403
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4936996.html
Copyright © 2011-2022 走看看