AC,Runtime: 16ms c++


  • 0
    T
    class Solution {
    public:
        string longestCommonPrefix(vector<string> &strs) {
            string ans;
            if (strs.size() == 0) return ans;
            int size = strs.size();
            
            
            int minLen = INT_MAX;
            for(vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
            {
                if ((*it).size() < minLen) minLen = (*it).size();
            }
            
            for(int i = 0; i < minLen; i++)
            {
                bool flag = true;
                for(int j = 0; j < size-1; j++)
                {
                    if (strs[j][i] != strs[j+1][i])
                    {
                        flag = false;
                        break;
                    }
                }
                
                if (flag)
                    ans.push_back(strs[0][i]);
                else break;
            }
            
            return ans;
        }
    };

Log in to reply
 

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