My c++ 6ms solution


  • 0
    K
    class Solution {
    public:
        bool isValidSerialization(string preorder) {
            for(int i=0;i<(preorder.size()-1);i++){
                if(preorder[i]!=','&&preorder[i+1]!=','){
                    preorder.erase(i,1);
                    i--;
                }
            }
            //cout << preorder;
            int j=0;
            while(1){
                int k=0;
                for(int i=2;i<(preorder.size()-2);i++){
                    if(i>preorder.size()){
                        break;
                    }
                
                    if(preorder[i]=='#'&&preorder[i+1]==','&&preorder[i+2]=='#'&&preorder[i-2]!='#'){
                        preorder.erase(i-2,4);
                        k=1;
                    }
                }
                if(k==0){
                    break;
                }
                j++;
            }
            //cout << preorder;
            if((preorder.size()==1&&preorder[0]=='#')||(preorder.size()==2&&preorder[0]=='#')){
                return true;
            }
            else {
                return false;
            }
        }
        
    };
    

    I was able to pass all the test cases but the code showed me error if i did not use

    if(i>preorder.size()){
                        break;
                    }
    

    which should not happen as i already have i<(preorder.size()-2) in for loop condition . I do not know why but the loop kept running for i=72 and preorder.size()=1 which does not make sense can someone tell me the mistake.


Log in to reply
 

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