-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreduce_string_using_stack.py
More file actions
76 lines (71 loc) · 1.7 KB
/
reduce_string_using_stack.py
File metadata and controls
76 lines (71 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# Steve has a string, , consisting of lowercase English alphabetic letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.
#
# Steve wants to reduce as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Steve out by finding and printing 's non-reducible form!
#
# Note: If the final string is empty, print Empty String .
#
# Input Format
#
# A single string, .
#
# Constraints
#
# Output Format
#
# If the final string is empty, print Empty String; otherwise, print the final non-reducible string.
#
# Sample Input 0
#
# aaabccddd
# Sample Output 0
#
# abd
# Sample Case 0
#
# Steve can perform the following sequence of operations to get the final string:
#
# aaabccddd → abccddd
# abccddd → abddd
# abddd → abd
# Thus, we print abd.
#
# Sample Input 1
#
# baab
# Sample Output 1
#
# Empty String
# Explanation 1
#
# Steve can perform the following sequence of operations to get the final string:
#
# baab → bb
# bb → Empty String
# Thus, we print Empty String.
#
# Sample Input 2
#
# aa
# Sample Output 2
#
# Empty String
# Explanation 2
#
# Steve can perform the following sequence of operations to get the final string:
#
# aa → Empty String
# Thus, we print Empty String.
import fileinput
def reduce(text):
items = list()
for i in range(0, len(text)):
if len(items) == 0:
items.append(text[i])
elif text[i] == items[-1]:
items.pop()
else:
items.append(text[i])
return ''.join(items) if items else "Empty String"
for line in fileinput.input():
pass
print(reduce(line))