One question of the day Leetcode844 compares strings with backspace

Leetcode844 compares strings with backspace

Title description:

Given two strings of S and T, when they are input into a blank text editor, judge whether they are equal, and return the result. # Represents the backspace character.

Note: If you enter a backspace character for empty text, the text will remain empty.

Example 1:

Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T will become "ac".

Example 2:

Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T will become "".

Example three:

Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T will become "c".

Example four:

Input: S = "a#c", T = "b"
Output: false
Explanation: S will become "c", but T will still be "b".

answer:

You can define a function callBack, the specific operations are as follows:
1. Define an empty string type string.
2. Traverse the characters in the string to be processed. If the character is'#' and the new string is not empty, use the pop_back() function to return the new string. Otherwise, use push_back() to increase the character.
Then finally compare the two processed strings for equality.

AC code

class Solution {
    
    
public:
    string callBack(string s){
    
    
        string rs;
        for(int i = 0; i < s.size(); i++){
    
    
            if(s[i] == '#'){
    
    
                if(!rs.empty())
                    rs.pop_back();
            }
            else
                rs.push_back(s[i]);
        }
        return rs;
    }
    bool backspaceCompare(string S, string T) {
    
    
        return callBack(S)==callBack(T);
    }
};

Welcome to reprint, indicate the source.

Question source: LeetCode
Link: https://leetcode-cn.com/problems/backspace-string-compare/

Guess you like

Origin blog.csdn.net/qq_36583373/article/details/109249906