Last active
April 29, 2021 14:01
-
-
Save mfaani/d0958d5c40821dffe42b20d1962517bd to your computer and use it in GitHub Desktop.
Valid Parentheses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
var remaining : [String: Int] = ["(": 0, "[": 0, "{": 0] | |
func isValid(_ s: String) -> Bool { | |
let validChars = ["(", ")", "[", "]","{", "}"] | |
let opens = ["[", "(", "{"] | |
let closes = ["]", ")", "}"] | |
for c in s { | |
let c = String(c) | |
guard remainingCloseFor(c) >= 0 else { | |
print("1") | |
return false | |
} | |
} | |
for (_, val) in remaining { | |
guard val == 0 else { | |
print("2") | |
return false | |
} | |
} | |
return true | |
} | |
var lastOpenedStack: [String] = [] | |
func remainingCloseFor(_ char: String) -> Int { | |
// opening | |
if let val = remaining[char] { | |
remaining[char] = val + 1 | |
lastOpenedStack.append(char) | |
return remaining[char]! | |
} else { | |
// closing | |
let correspondingOpen: String | |
if char == ")" { | |
remaining["("] = remaining["("]! - 1 | |
correspondingOpen = "(" | |
if lastOpenedStack.last != "(" { | |
remaining["("] = -1 | |
print("4") | |
} else { | |
lastOpenedStack.removeLast() | |
} | |
} else if char == "]" { | |
remaining["["] = remaining["["]! - 1 | |
correspondingOpen = "[" | |
if lastOpenedStack.last != "[" { | |
remaining["["] = -1 | |
print("5") | |
} else { | |
lastOpenedStack.removeLast() | |
} | |
} else { | |
remaining["{"] = remaining["{"]! - 1 | |
correspondingOpen = "{" | |
if lastOpenedStack.last != "{" { | |
remaining["{"] = -1 | |
print("6", lastOpenedStack) | |
}else { | |
lastOpenedStack.removeLast() | |
} | |
} | |
return remaining[correspondingOpen]! | |
} | |
} | |
// What I learned: | |
// When I close, it has to be for last opened items | |
// When something requires 'last' foo, then it might be a good indication that a stack is needed. | |
// If we need to pop the last item and go to a previous item, then 110% a stack is needed | |
// If you're trying to build relationships then dictionaries are the best. | |
// DON'T BE AFRAID TO CREATE MULTIPLE STATE HOLDING VARIABLES. | |
// DON'T TRY TO ENCAPSULATE ALL STATES INTO A SINGLLE MASSIVE VARIABLE | |
// Anything that causes an exit, return `false` can perhap be bubbled up/out | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That being said, I believe there should be solutions with less code