【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;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM