![]() |
VOOZH | about |
Given two strings s1 and s2, let us assume that while typing the strings there were some backspaces encountered which are represented by #. The task is to determine whether the resultant strings after processing the backspace character would be equal or not.
Examples:
Input: s1= geee#e#ks, s2 = gee##eeks
Output: True
Explanation: Both the strings after processing the backspace character becomes "geeeeks". Hence, true.Input: s1 = equ#ual, s2 = ee#quaal#
Output: False
Explanation: String 1 = equ#ual, after processing the backspace character becomes "equal" whereas string 2 = equ#ual, after processing the backspace character becomes "equaa". Hence, false.
Approach:
To solve the problem mentioned above we have to observe that if the first character is '#', that is there is certainly no character typed initially and hence we perform no operation. When we encounter any character other than '#', then we add the character just after the current index. When we encounter a '#', we move one index back, so instead of deleting the character, we just ignore it. Then finally compare the two strings by comparing each character from start to end.
Below is the implementation of the above approach:
False
Time Complexity: O(N)
Auxiliary Space: O(1)
Another Approach: (Using Stack)
The idea is to use a stack that stores the last occurrence of a character other than "#" (i.e, Backspace) and iterate over the each given string and if we find any character other than '#' then we keep storing it into the stack otherwise remove the last occurred character which is store into the stack. Do the Similar process for both given strings and check if both strings are equal then print "Yes" otherwise "No".
Following is the implementation of the above approach:
True
Time Complexity: O(n), Where n is the length of the given string
Auxiliary Space: O(n)