Problem of the day
Ninja wants to print two strings in a text editor but his keyword allows typing lowercase English letters and backspace only.
Ninja type ‘N’ characters given by string ‘STR1’ to print the first string in the editor, and type ‘M’ characters given by string ‘STR2’ to print the second string. Both ‘STR1’ and ‘STR2’ have lowercase English characters and ‘#’ to denote backspace.
Your task is to return true if both strings that print on the text editor are equal otherwise return false. See the example for more clarity.
Note:Backspace has no effect on empty text.
Example:
Consider ‘STR1’ = “ade##c#ba”, ‘STR2 = ‘a#ad#b#ba
Both ‘STR1’ and ‘STR2’ print the string “aba” on the text editor, thus we should return true.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain two space-separated strings ‘STR1’ and ’STR2’ respectively.
Output Format:
For each test case, print “true” if both strings that print on the text editor are equals otherwise print “false”
Output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of.
1 <= T <= 50
2 <= N <= 10000
0 <= M <= 10000
Time limit: 1 sec
2
ab## c#d###
ade##c#ba a#ad#b#ba
true
true
In the first test case, Both of them print empty strings.
For the second test case, see the problem statement for an explanation.
2
a#c b
c#c#c ccc#c#
false
false
Use stack to build both strings independently.
We use a stack to simulate typing of each character. When ninja type backspace we pop the top character from the string otherwise we push the typed character on top of the string.
The steps are as follows:
O(N + M), where 'N' is the length of ‘STR1’ and ‘M’ is the length of ‘STR2’.
Push and Pop operations on stack take O(1) times, Here in the first loop we perform at most ‘N’ such operations, and in the second loop we perform ‘M’ such operations, Thus the overall time complexity will be O(N + M).
O(N + M), where 'N' is the length of ‘STR1’ and ‘M’ is the length of ‘STR2’.
Space used by stack ‘STK1’ will be at most O(N) and space used by stack ‘STK2’ will be at most O(M). Thus the overall space complexity will be O(N + M).