simple c++ solution 6 ms


  • 0
    T
    /*
    1, Pick a character at i=0th location and compare it with the character at that location in every string.
    
    2, If anyone doesn't have that just return ""
    
    3, Else append that character in to the result.
    
    4, Increment i and do steps 1-3 till the length of that string.
    
    5, return result.
    
    */
    
    
    class Solution {
    public:
    
        string cmp(string &str1, string &str2) {
            string ret;
            int i = 0;
            for (; i < str1.length() && i < str2.length(); i++) {
                if (str1[i] != str2[i])
                    break;
            }
            ret = str1.substr(0, i);
            return ret;
        }
    
        string longestCommonPrefix(vector<string>& strs) {
            if (strs.size() == 0) return "";
            string result = strs[0];
            
            for (int i = 1; i < strs.size(); i++) {
                result = cmp(result, strs[i]);
                if (result == "") return "";
            }
    
            return result;
        }
    };
    

Log in to reply
 

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