【LeetCode】14. Longest Common Prefix (2 solutions)

Longest Common Prefix

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

解法一:

思路:设置一个位数记录器num,遍历所有字符串的第num位。如果都相同,则num++。

直到某字符串结束或者所有字符串的第num位不都相同,则返回[0~num-1]位,即最长公共前缀。

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if(strs.empty())
            return "";
        else if(strs.size() == 1)
            return strs[0];
        else
        {
            string ret = "";
            int num = 0;
            char c = strs[0][num];
            while(true)
            {
                for(vector<string>::size_type st = 0; st < strs.size(); st ++)
                {
                    if(num < strs[st].size() && strs[st][num] == c)
                    {//match
                        if(st == strs.size()-1)
                        {//end
                            ret += c;
                            num ++;
                            c = strs[0][num];
                        }
                    }
                    else
                        return ret;
                }
            }
        }
    }
    
};

解法二:

类似解法一,换个写法。

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        string ret = "";
        char c;
        int index = 0;
        if(strs.empty())
            return ret;
        while(true)
        {
            for(int i = 0; i < strs.size(); i ++)
            {
                if(i == 0)
                {
                    if(index < strs[0].size())
                        c = strs[0][index];
                    else
                        return ret;
                }
                // no else, 0 may equals to strs.size()-1
                if(i == strs.size()-1)
                {
                    if(index >= strs[i].size() || strs[i][index] != c)
                        return ret;
                    else
                    {
                        ret += c;
                        index ++;
                    }
                }
                if(i != 0 && i != strs.size()-1)
                {
                    if(index >= strs[i].size() || strs[i][index] != c)
                        return ret;
                }
            }
        }
        return ret;
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4073386.html