zoukankan      html  css  js  c++  java
  • 14. Longest Common Prefix最大前缀

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

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

    找出一堆字符串,相同前缀,如:abcdhewuhf,abcjjee,abcd 的最大前缀是abc

    一遍过,提交成功--

    另外,关于vector的使用,如vector类型strs,想要得到vector类型变量容器中数据个数,用自身函数:strs.capacity()

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(0 == strs.capacity()) return "";      //输入数据量为空的时候,返回空字符串
            int n = strs[0].length();                //初始时,最大前缀假设为第一个字符串的长度
            string prefix = strs[0];
            for( int i = 1; i < strs.capacity(); i++){
                if(strs[i].length() < n ) n = strs[i].length();      //某个字符串长度小于最大前缀长度时,改变最大前缀长度
                for(int j = 0; j < n; j++){
                    if(prefix[j] != strs[i][j]){
                        n = j;
                        break;
                    }
                }
                
            }
            return prefix.substr(0,n);
        }
    };
  • 相关阅读:
    C++ Primer 第五版-1.1
    C++ Primer 第五版笔记-1.0
    TouchID
    正则表达式
    duplicate symbol 错误
    第三方登录
    AFNetWorking
    IOS---通知
    左右点击--日期增减
    Xcode相关设置
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7806043.html
Copyright © 2011-2022 走看看