844. Compares strings containing backspace

Given two strings, s and t, when each is entered into a blank text editor, determine whether the two are equal. # stands for backspace character.

Return true if equal; Otherwise, return false.

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

Example 1:

Input: s = "ab#c", t = "ad#c" output: true explanation: both s and t become "ac".Copy the code

Example 2:

Input: s = "ab##", t = "c#d#" output: trueCopy the code

Example 3:

Input: s = "a##c", t = "#a#c" output: true explanation: both s and t become "c".Copy the code

Tip:

  • 1 <= s.length, t.length <= 200
  • s 和 tContains only lowercase letters and charactersThe '#'

Refactoring string

Train of thought

We remove the # and the preceding character from the string to get a valid string and then compare

Write a function that handles strings

  • The newStr function declares a new variable to hold the new string
  • Traversing the string, we truncate the end of newStr when # is encountered, and append the rest of the string to the end

Compare two strings with a function

var backspaceCompare = function (s, t) {
    function dealStr(str) {
        var index = 0;
        var newStr = ' '
        while (index < str.length) {
            var item = str[index];
            if (item === The '#' && newStr.length > 0) {
                newStr = newStr.slice(0, newStr.length - 1)}if(item ! = =The '#') {
                newStr += item
            }
            index++
        }
        return newStr
    }
    if (dealStr(s) === dealStr(t)) {
        return true
    }
    return false
};
Copy the code