C++ 4ms solution


  • 0
    D
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(strs.size() == 0) return "";
            string lcp = strs[0];
            for(auto &s : strs) {
                if(lcp == "") return lcp;
                lcp = lcp.substr(0, s.size());
                for(int i = 0; i < s.size(); i++) {
                    if(lcp[i] != s[i]) {
                        lcp = lcp.substr(0, i);
                        break;
                    }
                }
            }
            return lcp;
        }
    };
    

Log in to reply
 

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