• 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;
        }
    };
  • 相关阅读:
    [leetcode-91-Decode Ways]
    [leetcode-72-Edit Distance]
    [leetcode-67-Add Binary]
    [leetcode-137-Single Number II]
    [leetcode-60-Permutation Sequence]
    [leetcode-55-Jump Game]
    [leetcode-18-4Sum]
    [leetcode-15-3Sum]
    [leetcode-47-Permutations II]
    easyui tabs update 强制刷新页面
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4438874.html
Copyright © 2020-2023  润新知