C++simple solution


  • 0
    Y
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(strs.size() == 0) return "";
            string res = strs[0];
            for(int i = 1; i < strs.size(); i++) {
                if(res[0] != strs[i][0]) return "";
                for(int j = 1; j < min(res.size(),strs[i].size()); j++){
                    if(res[j] != strs[i][j]) {
                        res = res.substr(0,j);
                        break;
                    }
                }
                res = (res.size() > strs[i].size())?strs[i]:res;
            }
            return res;
        }
    };

Log in to reply
 

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