DEV Community

Discussion on: Daily Challenge #206 - Pound Means Backspace

Collapse
 
vidit1999 profile image
Vidit Sarkar

Hope this is right, C++

string cleanString(string s){
    string ans = ""; // the answer string
    int length = 0; // length of answer string
    for(char c : s){

        if(c == '#'){
            // if c == '#' and length > 0, then pop one character and decrement length
            if(length > 0){
                ans.pop_back();
                length--;
            }
        }
        // else add the character to string and increment length
        else{
            ans += c;
            length++;
        }
    }

    return ans;
}