Simplest c++ solution 15ms with comments


  • 0
    R
    class Solution {
    public:
        string longestCommonPrefix(vector<string> &strs) {
            int m = strs.size();
            string ret = "";
            if(m == 0)
                return ret;
            //get the length of any string
            int n = strs[0].length();
            bool flag; //flag to check if match fails
            for(int i=0;i<n;i++) {
                flag = false;
                for(int j=1;j<m;j++) {
                    // check if any string doesn't match at position i
                    if(strs[j][i] != strs[j-1][i]) {
                        flag = true; // make flag to be true
                        break;
                    }
                }
                //if every string has same character (flag isn't true)
                if(flag) {
                    break; //break if true - done!
                }
                else {
                    //else append the char to our return string 
                    ret += strs[0][i];
                }
            }
            return ret;
        }
    };

Log in to reply
 

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