zoukankan      html  css  js  c++  java
  • 力扣(LeetCode)试题14-最长公共前缀 C++代码

    更新啦,力扣编译可以通过了,最长公共部分待考虑

    算法若容器中没有元素,直接返回空

    令第一个字符串为初始公共前缀,使用此公共前缀与下一个字符串比较得到新的公共前缀,新公共前缀与再下一个字符串比较…直到和最后一个字符串比较,此时得到的公共前缀就是这些字符串的公共前缀

     1 #include <iostream>
     2 #include <string>
     3 #include <vector>
     4 #include <algorithm>
     5 
     6 using namespace std;
     7 
     8 class Solution {
     9 public:
    10     string longestCommonPrefix(vector<string>& strs)
    11     {
    12         string result;
    13         if (strs.size() == 0) return "";
    14         else
    15         {
    16             string temp = strs[0];//将第一个串作为公共前缀
    17             for (int i = 1; i < strs.size(); i++)//外循环,公共前缀与每个串进行比较
    18             {
    19                 int min_val = min(temp.length(), strs[i].length());//取公共前缀与下一个串最小值
    20                 int index;//索引
    21                 if (min_val == 0) return ""; //比较过程中,某个串儿为空,则返回空
    22                 else
    23                 {
    24                     for (int j = 0; j < min_val; j++)
    25                     {
    26                         if (temp[j] == strs[i][j])
    27                         {
    28                             index = j;
    29                             continue;
    30                         }
    31                         else
    32                         {
    33                             temp = temp.substr(0, j);
    34                             break;
    35                         }
    36                     }
    37                     temp = temp.substr(0, index + 1);
    38                 }
    39 
    40             }
    41             result = temp;//外循环结束,将temp值赋值给result
    42 
    43         }
    44         return result;
    45     }
    46 };
    47 
    48 int main(){
    49     vector<string> str{ "aa", "a", ""};
    50     Solution sol;
    51     string result = sol.longestCommonPrefix(str);
    52 
    53     cout << result << endl;
    54 
    55     int w;
    56     cin >> w;
    57     return 0;
    58 }

     

  • 相关阅读:
    C语言经典算法100例(二)
    Plus One @LeetCode
    hdu 4099 Revenge of Fibonacci 字典树+大数
    算法入门系列一--DP初步
    《当裸辞的程序猿遇上最冷季八》——第一次约女孩吃饭
    UVa 297
    手机NFC通信的安全车钥匙
    innosetup卸载软件后,删除定时任务schedule task
    VS2008调试程序时出现"XXX mutex not created."
    centOS7关闭防火墙的命令
  • 原文地址:https://www.cnblogs.com/pgzhanglin/p/13217903.html
Copyright © 2011-2022 走看看