LeetCode844: Compare strings with backspace

1. Title description

Given two strings of S and T, when they are input into a blank text editor, determine 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 3:

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

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

prompt:

  1. 1 <= S.length <= 200
  2. 1 <= T.length <= 200
  3. SAnd Tonly contain lowercase letters and characters '#'.

Two, algorithm ideas

First determine the data structure used in the question

Two strings, enter, if you encounter #, delete the previous one. This is like writing a document, writing first and deleting last. You can use the stack structure

Finally, you need to compare whether the two strings are equal, then you need two stacks, one stack stores one string

  1. Convert string to character array
  2. Traverse the character array, push the stack if it is not #, and pop it if it is # and the stack is not empty. Write two for loops to load character arrays into two stacks
  3. Use the equals method of the stack to compare the contents of the two stacks, the same returns true, and different returns false

Three, code implementation

    public static boolean backspaceCompare(String S, String T) {
    
    

        //创建两个栈存放字符串
        Stack stack1 = new Stack();
        Stack stack2 = new Stack();

        //将字符串转换为字符数组
        char[] c1 = S.toCharArray();
        char[] c2 = T.toCharArray();

        //给栈1装入数据
        for (int i = 0;i < c1.length;i++){
    
    
            if (c1[i] != '#'){
    
    
                stack1.push(c1[i]);
            }else if (c1[i] == '#' && !stack1.isEmpty()){
    
    
                stack1.pop();
            }
        }
        //给栈2装入数据
        for (int i = 0;i < c2.length;i++){
    
    
            if (c2[i] != '#'){
    
    
                stack2.push(c2[i]);
            }else if (c2[i] == '#' && !stack2.isEmpty()){
    
    
                stack2.pop();
            }
        }

        //判断栈的内容是否相等
        if (stack1.equals(stack2)){
    
    
            return true;
        }else {
    
    
            return false;
        }

    }

Guess you like

Origin blog.csdn.net/weixin_45321793/article/details/110553927
Recommended