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;
        }
    };
  • 相关阅读:
    MFC 按钮
    读写文件
    遍历一个文件夹所有文件
    Java的运行机制
    selenium学习笔记——高级操作
    selenium学习笔记——定位元素
    selenium学习笔记——介绍&环境准备
    搭建安卓系统的测试环境
    Linux下Java环境的安装与配置
    Linux的目录结构介绍
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4438874.html
Copyright © 2011-2022 走看看