diff --git a/020-valid-parentheses/memo.md b/020-valid-parentheses/memo.md new file mode 100644 index 0000000..d33e94a --- /dev/null +++ b/020-valid-parentheses/memo.md @@ -0,0 +1,22 @@ +## step1で考えたこと + +それぞれの括弧に対応するものを取り除いていき、最後に残っていればFalse, そうでないならTrue + +=> whileの終了条件をどうするか? +無限ループになってしまう +さらにStep1のコードだと本来FalseであるべきものもTrueになってしまう + +カッコを分けて取り除くのではなく、セットで取り除けば良いのでは?? + +## step2 +コードは適切に求められたことを処理できているがRuntimeが若干遅いのが気になる +Time Complexity: O(n^2). +Space Complexity: O(n). +=> Brute Force + + +もっと早くするにはどうすべきか +- whileを使わないで書く +=> Using stack + +## step3 diff --git a/020-valid-parentheses/step1.py b/020-valid-parentheses/step1.py new file mode 100644 index 0000000..ef172e0 --- /dev/null +++ b/020-valid-parentheses/step1.py @@ -0,0 +1,30 @@ +# 動かないコード + +class Solution: + def isValid(self, s: str) -> bool: + while s: + if "(" in s: + s.pop("(") + s.pop(")") + elif "[" in s: + s.pop("[") + s.pop("]") + elif "{" in s: + s.pop("{") + s.pop("}") + + return True + +class Solution: + def isValid(self, s: str) -> bool: + while s: + if "()" in s: + s = s.replace("()", "") + elif "[]" in s: + s = s.replace("[]", "") + elif "{}" in s: + s = s.replace("{}", "") + + # return not s と書くのが簡潔でわかりやすい。 + if s: return True + else: return False diff --git a/020-valid-parentheses/step2.py b/020-valid-parentheses/step2.py new file mode 100644 index 0000000..cf40042 --- /dev/null +++ b/020-valid-parentheses/step2.py @@ -0,0 +1,8 @@ +# 以前見つけた回答を一度見てから自力で書いたコード +class Solution: + def isValid(self, s: str) -> bool: + while "()" in s or "[]" in s or "{}" in s: + s = s.replace("()", "") + s = s.replace("[]", "") + s = s.replace("{}", "") + return s == "" \ No newline at end of file diff --git a/020-valid-parentheses/step3.py b/020-valid-parentheses/step3.py new file mode 100644 index 0000000..5c275fa --- /dev/null +++ b/020-valid-parentheses/step3.py @@ -0,0 +1,15 @@ +## 別解 +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + open_to_close = {"()": ")", "[]": "]", "{": "}"} + + for c in s: + if c in open_to_close: + if stack and stack[-1] == open_to_close[c]: + stack.pop() + else: + return False + else: + stack.append(c) + return True if not stack else False \ No newline at end of file