Google | Phone Screen | Backspace String Compare
Anonymous User
1588
Sep 27, 2019
Sep 27, 2019

You can input 27 keys: 26 English letters (lower cases only) and a backspace key (represented by ‘-’ below).

Write a function to compare two key input sequences, return True if they produce equivalent display output; otherwise False.

Example 1:
'a-bc-d' (one backspace) is equivalent to 'bd'

Example 2:
'--cd--e' (two backspaces) is not equivalent to '--e'


I thought of using stack to resolve it as follows. Is there any better solution?

def simplify(self, input_string):
	output_string = []
	for i in input_string:
	if i == "-":
		if output_string:
			output_string.pop()
	else:
                output_string.append(i)
        return output_string

def compare_string(self, str_a, str_b):
        return True if self.simplify(str_a) == self.simplify(str_b) else False
Comments (2)