본문 바로가기

Leetcode98

[LeetCode] Number of Segments in a String 파이썬 (white space as None) class Solution: def countSegments(self, s: str) -> int: return len([i for i in s.strip().split(' ') if i]) strip은 안전하게 양쪽 끝의 공백을 제거하는 용도로 넣어준 듯. if i 라는 조건을 통해 whitespace가 아닐 경우만 새로운 list의 원소로 추가. str.strip str.strip([chars]) Return a copy of the string with the leading and trailing characters removed. 2021. 4. 16.
[LeetCode] Fizz Buzz 파이썬 (여러 솔루션) class Solution: def fizzBuzz(self, n: int) -> List[str]: res = [] k = 1 while k 2021. 4. 16.
[LeetCode] Longest Palindrome 파이썬 (bitwise &, Counter) from collections import Counter class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: int """ odds = 0 for k, v in Counter(s).items(): odds += v & 1 return len(s) - odds + int(odds > 0) lambda, map을 사용해서 홀 수 인 s 구하기 def longestPalindrome2(self, s): """ :type s: str :rtype: int """ odd = sum(map(lambda x: x & 1, Counter(s).values())) return len(s) - odd + int(odd > 0) 홀.. 2021. 4. 16.
[LeetCode] Sum of Left Leaves 파이썬 (Tree) class Solution(object): def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int """ def sumOfLeftLeavesHelper(root, is_left): if not root: return 0 if not root.left and not root.right: return root.val if is_left else 0 return sumOfLeftLeavesHelper(root.left, True) + sumOfLeftLeavesHelper(root.right, False) return sumOfLeftLeavesHelper(root, False) leaf 노드 까지 탐색한다. left일 경우에만 + 출처: .. 2021. 4. 15.
[LeetCode] Is Subsequence 파이썬 (pointer, relative position) class Solution: def isSubsequence(self, s: str, t: str) -> bool: if not s: return True i = 0 for c in t: if c == s[i]: i += 1 if i == len(s): return True return False i를 pointer로 사용해서 relative position 위치 정보를 고려해서 순차적으로 i를 하나씩 업데이트 다 찾은 경우 (i==len(s)) return. 출처: github.com/jiapengwen/LeetCode/blob/master/Python/is-subsequence.py 2021. 4. 15.
[LeetCode] Find the Difference 파이썬 (Counter, A.subtract(B), bit operation, xor, reduce) from collections import Counter class Solution: def findTheDifference(self, s: str, t: str) -> str: if len(s) == 0: return t # s = "" S = Counter(s) T = Counter(t) T.subtract(S) # inplace res = [k for k, v in T.items() if v > 0] return res[0] Counter 클래스에는 subtract라는 메서드가 있다. inplace이기 때문에 이 점을 유의할 것. 다른 풀이들 class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str.. 2021. 4. 14.
[LeetCode] First Unique Character in a String 파이썬 (Counter, str.find) from collections import Counter class Solution: def firstUniqChar(self, s: str) -> int: idx = -1 c = Counter(s) # print(c) idx_list = [] for k,v in c.items(): # print(k,v) if v == 1: idx = s.index(k) return idx else: return idx Counter 클래스를 사용해서 풀었다. counter를 찍어보니 Counter({'e': 3, 'l': 1, 't': 1, 'c': 1, 'o': 1, 'd': 1}) 이런식으로 value 순으로 descending order로 출력은 되는데 실제 items로 iterate 해보면 입력순으로, 즉, l.. 2021. 4. 14.
[LeetCode] Ransom Note 파이썬 (dict, set, count) from collections import defaultdict class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: seen = defaultdict(int) for r in ransomNote: seen[r] += 1 for m in magazine: if m in seen: seen[m] -= 1 for v in seen.values(): if v > 0: return False return True "fihjjjjei" "hjibagacbhadfaefdjaeaebgi" defaultdict(, {'f': -1, 'i': 0, 'h': -1, 'j': 2, 'e': -2}) seen 이라는 dict에 0보다 큰.. 2021. 4. 14.
[LeetCode] Guess Number Higher or Lower 파이썬 (binary search) while 문으로 해결하려 했더니 시간초과 Binary Search로 풀어야 함. # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int) -> int: left, right = 1, n while left 2021. 4. 14.