Isomorphic Strings

https://leetcode.com/problems/isomorphic-strings/ s と t をマッピングして考える。 この際、同じ文字なのに違う文字がマッピングされる場合 isomorphic にならない。 ex. foo bar | f → b | | o → a | | o → r | | b → f | | a → o | | r → o | o が a と r にマッピングされているので、 isomorphic にならず、false になる。 class Solution: def isIsomorphic(self, s: str, t: str) -> bool: mapST, mapTS = {}, {} for c1, c2 in zip(s, t): if((c1 in mapST and mapST[c1] !...

October 21, 2021

Valid Anagram

anagram かどうかを調べるには s, t の出現する文字のカウントが同じなら anagram と言える。 回答方法は 文字数をカウントし、s と t を比較する 文字数をカウントし、s と t を比較する(Counter を使う) sorted を使う Input: s = “anagram”, t = “nagaram” 文字数をカウントし、s と t を比較する class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s)!= len(t): return False count_s, count_t = {}, {} for i in range(len(s)): count_s[s[i]] = 1 + count_s.get(s[i], 0) count_t[t[i]] = 1 + count_t.get(t[i], 0) for c in count_s: if count_s[c] !...

October 20, 2021

Valid Parentheses

https://leetcode.com/problems/valid-parentheses/ Prerequisite Hash Map Stack 最初にどのカッコがどの 括弧閉じ にマッチしているかわかるために HashMap を作る必要がある。 この際、括弧閉じ をキーにする。 for 文で list の中を確認し、 括弧開きは stack に入れる。 stack は 最後に入れたものから出すので、 括弧開き と 括弧閉じ がマッチしていれば、 stack から pop できる。 最後に stack に何も残らなければ、 全てがマッチして True を return する。 Time complexity: O(n) Mem complexity: O(n) class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] closeToOpen = { ')' : '(', ']' : '[', '}' : '{' } for c in s: if c in closeToOpen: if stack and stack[-1] == closeToOpen[c]: stack....

September 22, 2021