Repository navigation
Expand file tree
/
Copy pathcorrect_valid_parenthesis_string.py
More file actions
129 lines (114 loc) · 3.58 KB
/
Copy pathcorrect_valid_parenthesis_string.py
File metadata and controls
129 lines (114 loc) · 3.58 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def checkValidString(s: str) -> bool:
min_open = 0 # Minimum possible open parentheses
max_open = 0 # Maximum possible open parentheses
for char in s:
if char == '(':
min_open += 1
max_open += 1
elif char == ')':
min_open -= 1
max_open -= 1
else: # char == '*'
min_open -= 1 # Treat as ')'
max_open += 1 # Treat as '('
# If max_open becomes negative, we have too many closing parentheses
if max_open < 0:
return False
# min_open should never go below 0 (can't have negative open parentheses)
min_open = max(min_open, 0)
# Valid if we can have exactly 0 open parentheses at the end
return min_open <= 0 <= max_open
def checkValidString_alternative(s: str) -> bool:
"""
Alternative solution using two passes
"""
# First pass: left to right, treat '*' as '('
balance = 0
for char in s:
if char in '(*':
balance += 1
else: # char == ')'
balance -= 1
if balance < 0:
return False
# Second pass: right to left, treat '*' as ')'
balance = 0
for char in reversed(s):
if char in ')*':
balance += 1
else: # char == '('
balance -= 1
if balance < 0:
return False
return True
# Test cases
test_cases = [
("()", True),
("(*)", True),
("(*))", True),
("(()", False),
("*)", True),
("(*", True),
("**", True),
("(*))", True),
("(((*", True),
("*)))", False),
("", True),
"*", # Should be True
"(**(*()**()**((**(*)", # Complex case
]
print("Testing correct solutions:")
print("\nMethod 1 (Range tracking):")
for case in test_cases:
if isinstance(case, tuple):
s, expected = case
result = checkValidString(s)
status = "✓" if result == expected else "✗"
print(f"{status} '{s}' -> {result} (expected: {expected})")
else:
result = checkValidString(case)
print(f"'{case}' -> {result}")
print("\nMethod 2 (Two passes):")
for case in test_cases:
if isinstance(case, tuple):
s, expected = case
result = checkValidString_alternative(s)
status = "✓" if result == expected else "✗"
print(f"{status} '{s}' -> {result} (expected: {expected})")
else:
result = checkValidString_alternative(case)
print(f"'{case}' -> {result}")
# Your original solution for comparison
def your_checkValidString(s: str) -> bool:
stack = []
backtrack = s[0] if s else ""
star_char = ""
for ch in s:
if ch == "(":
backtrack = ch
stack.append(")")
elif ch == ")" and len(stack) != 0:
backtrack = ch
stack.pop()
# The star condition
else:
if backtrack == "(":
star_char = ")"
elif backtrack == ")":
star_char = "("
else:
star_char = ""
if star_char == ")" and len(stack) != 0:
stack.pop()
elif star_char == "(":
stack.append(")")
else:
if len(stack) != 0:
stack.pop()
return len(stack) == 0
print("\nYour original solution:")
simple_tests = [("()", True), ("(*)", True), ("(*))", True), ("(()", False)]
for s, expected in simple_tests:
result = your_checkValidString(s)
status = "✓" if result == expected else "✗"
print(f"{status} '{s}' -> {result} (expected: {expected})")