C++ simple ans easy-understanding


  • 1
    X
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if(strs.empty()){
                return "";
            }
            string ans = strs[0];
            for(int i = 1;i < strs.size(); ++i){
                int p = ans.length();
                int q = strs[i].length();
                int common = 0;
                for(int m = 0, n = 0; m < p && n < q; ++m, ++n){
                    if(ans[m] == strs[i][n]){
                        ++common;
                    }else{
                        break;
                    }
                }
                ans = ans.substr(0, common);
                if(ans == ""){
                    break;
                }
            }
            return ans;
        }
    };

Log in to reply
 

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