A 4ms C++ Solution


  • 0
    Y
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if((strs.size() == 0)) return "";
            if((strs.size() == 1)) return strs[0];
            int minlen = INT_MAX, j;
            string ans = "";
            bool flag = false;
            for(int i = 0; i < strs.size(); i++) {
                if(strs[i].length() < minlen) minlen = strs[i].length();
            }
            for(j = 0; j < minlen; j++) {
                for(int m = 0; m < strs.size() - 1; m++) {
                    if(strs[m][j] == strs[m + 1][j]) flag = true;
                    else {
                        flag = false;
                        break;
                    }
                }
                if(!flag) break;
            }
            for(int n = 0; n < j; n++) {
                ans += strs[0][n];
            }
            return ans;
        }
    };

Log in to reply
 

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