zoukankan      html  css  js  c++  java
  • Longest Common Prefix

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

    思路:这道题其实很简单。只不过一开始我就想复杂了,一看求Longest,就联想到DP。然后又联想到Set来求交并。

    后来,突然想到,其实一个string就能解决。

    :Prefix的最长长度,是由匹配度最低的那个string来决定的。

    假定A,B,C三个string,从前往后遍历vector的话,则一定满足len(prefix(A,B)) >= len(prefix(A,B,C))

    所以用一个string类型的res来记录就可以了。

    注意:返回空str,不能用NULL

    几乎是bug free,很开心

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            //check validation
            string res;
            if(strs.empty()) return res;
            //check special case or bound
            size_t n=strs.size();
            if(n==1) return strs[0];
            
            res=strs[0];
            string cur;
            for(int i=1;i<n;i++){
                if(res.empty()) break;
                cur=strs[i];
                int lres=res.length();
                int lcur=cur.length();
                int r=0;
                int s=0;
                bool endloop=false;
                while(r<lres && s<lcur && !endloop){
                    if(res[r]!=cur[s]) endloop=true;
                    else {
                        r++;
                        s++;
                    }
                }
                res=res.substr(0,r);
            }
            return res;
        }
    };
  • 相关阅读:
    网络基础之网络协议篇
    JVM-07-执行引擎
    JVM-06-对象实例化、内存布局、访问定位以及直接内存
    JVM-05-方法区
    JVM-04-堆
    JVM-03-本地方法接口和本地方法栈
    JVM-02-程序计数器 虚拟机栈
    JVM-01-类加载子系统
    JVM-00-引言
    swagger
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4438874.html
Copyright © 2011-2022 走看看