C++ Solution Clean and Elegant


  • 0
    S

    class Solution {
    public:
    string longestCommonPrefix(vector<string>& strs) {

        int arrSize = strs.size();
        string str = "";
        if(arrSize == 0)
            return str;
        else if(arrSize == 1)
            return strs[0];
        else
        {
            int count = 0;
            while(true)
            {
                if(strs[0].length() >= count + 1)
                {
                    for(int i = 1; i < arrSize; i++)
                    {
                        if(strs[i].length() < count + 1)
                            return str;
                        else
                        {
                            if(strs[0][count] != strs[i][count])
                            return str;
                        }
                    }
                    str = str + strs[0][count];
                    count++;
                }
                else
                    return str;
            }
        }
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.