Strings - Backspace String Compare using JAVA Stack

Question: Given two Strings S and T, return true if they equal when both are typed out any "#" will be treated as backspace.

input - S -> ab#c, T -> az#c
output - True

Constraints need to ask because solution may change according to given constraints

Question: What happens when 2 or multiple "#" appear besides each other?
Answer: Delete same number of values before 1st "#". Ex- ab## -> ""

Question: What happen to "#" when there is no character to remove?
Answer: It deletes nothing. Ex- a###b -> "b"

Question: Are two empty Strings equals each other?
Answer: Ex- S -> a#b#c#, T -> c#. Both returns empty string and output will be true.

Question: Does case sensitivity matters?
Answer: Yes. Ex- A is different from a. S -> ab#c, T -> Az#c. Output - False

Solution using JAVA language.

BruteForce Approach - This is simple approach, We are using JAVA Stack here,
* Initialize 2 stacks for 2 Strings
* iterate one by one
* If character of String not equal to "#", add to stack using push()
* Else remove last element from stack using pop * Compare Both Stacks and return response.

import java.util.Stack;

public class  BackspaceStringCompare {
    public static void main(String[] args) {
        String s = "a#b#c#d";
        String t = "c#d";
        System.out.println(checkStrings(s, t));
    }

    private static boolean checkStrings(String s, String t) {
        Stack sStack = getResultStringInStack(s);
        Stack tStack = getResultStringInStack(t);

        if (sStack.size() != tStack.size()) {
            return false;
        }
        for (int i = 0; i < sStack.size(); i++) {
            if (sStack.elementAt(i) != tStack.elementAt(i)) {
                return false;
            }
        }
        return true;
    }

    private static Stack getResultStringInStack(String s) {
        Stack stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != '#') {
                stack.push(s.charAt(i));
            } else {
                if (stack.size() > 0) {
                    stack.pop();
                }
            }
        }
        return stack;
    }
}

/*
* Time complexity - O(a+b)
* Space complexity - O(a+b)
* a, b - length of strings S, T
* */

Comments

Popular posts from this blog

Arrays - Trapping Rainwater - Optimal Solution using 2 Pointer Approach

Arrays - Container with Most Water

Arrays - Two Sum