Valid Parenthesis String
LeetCode 678 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Two counters: optimistic opens forward, optimistic closes backward.
ನಾನು Valid Parenthesis String (LeetCode 678) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Parentheses / Bracket Matching ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Scan left to right treating every '*' as '(' — if the open count ever goes negative, there are too many ')'. Scan right to left treating every '*' as ')' — if that count goes negative, there are too many '('. Passing both means some assignment works.
Approach
- 1
openCount: +1 for '(' or '*', −1 for ')'.
- 2
closeCount (from the right): +1 for ')' or '*', −1 for '('.
- 3
Either negative → False.
- 4
Earlier version: two stacks of indices.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Two-direction countingPythonO(n) time · O(1) space
class Solution:
def checkValidString(self, s):
openCount = 0
closeCount = 0
n = len(s)
for i in range(n):
if s[i] == "(" or s[i] == "*":
openCount += 1
else:
openCount -= 1
if s[n - i - 1] == ")" or s[n - i - 1] == "*":
closeCount += 1
else:
closeCount -= 1
if openCount < 0 or closeCount < 0:
return False
return TrueValid Parenthesis String — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Valid Parenthesis String ಹಿಂದಿನ intuition ಏನು?
Scan left to right treating every '*' as '(' — if the open count ever goes negative, there are too many ')'. Scan right to left treating every '*' as ')' — if that count goes negative, there are too many '('. Passing both means some assignment works.
Valid Parenthesis String (LeetCode 678) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. openCount: +1 for '(' or '*', −1 for ')'. 2. closeCount (from the right): +1 for ')' or '*', −1 for '('. 3. Either negative → False. 4. Earlier version: two stacks of indices.
Valid Parenthesis String ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(1). (Accepted approach: Two-direction counting.)
Valid Parenthesis String ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
A '*' before a '(' can't close it — the stack version checks index order.