C++ easy to understand solution 6ms


  • 0
    J
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(strs.empty()) return "";
            if(strs.size() == 1) return strs[0];
            string prefix = "";
            int j = 0;
            while(1) {
                if(strs[0].empty()) return prefix;
                char tmp = strs[0][j];
                int same = 1;
                for(int i = 1;i < strs.size();i++) {
                    if(strs[i].size() < j + 1) return prefix;
                    same *= (strs[i][j] == tmp); 
                }
                if(same) {
                    prefix += tmp;
                    j++;
                }
                else return prefix;
            }
            return prefix;
        }
    };

Log in to reply
 

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