diff --git a/longest-palindromic-substring/Chaedie.py b/longest-palindromic-substring/Chaedie.py new file mode 100644 index 000000000..984ae8219 --- /dev/null +++ b/longest-palindromic-substring/Chaedie.py @@ -0,0 +1,40 @@ +""" +Solution: + 1) 포문을 돌면서 좌우 투포인터로 벌려주며 같은 문자인지 확인한다. 같으면 팰린드롬, 아니면 break + 2) 홀수, 짝수를 별도로 순회한다. + +Time: O(n^2) +Space: O(1) +""" + +class Solution: + def longestPalindrome(self, s: str) -> str: + result = s[0] + + for i in range(len(s)): + # check odd + word = s[i] + left, right = i - 1, i + 1 + while left >= 0 and right < len(s): + if s[left] == s[right]: + word = s[left] + word + s[right] + if len(result) < len(word): + result = word + left -= 1 + right += 1 + else: + break + + word = "" + left, right = i, i + 1 + while left >= 0 and right < len(s): + if s[left] == s[right]: + word = s[left] + word + s[right] + if len(result) < len(word): + result = word + left -= 1 + right += 1 + else: + break + + return result diff --git a/rotate-image/Chaedie.py b/rotate-image/Chaedie.py new file mode 100644 index 000000000..4ca5e706a --- /dev/null +++ b/rotate-image/Chaedie.py @@ -0,0 +1,32 @@ +""" +Solution: 1) 가장 바깥에서부터 안쪽으로 들어오며 4 원소의 자리를 바꿔준다. +Time: O(n^2) +Space: O(1) +""" + + +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + ROWS, COLS = len(matrix), len(matrix[0]) + + + l, r = 0, COLS - 1 + t, b = 0, ROWS - 1 + while l < r and t < b: + for i in range(r - l): + [ + matrix[t][l + i], + matrix[t + i][r], + matrix[b][r - i], + matrix[b - i][l] + ] = [ + matrix[b - i][l], + matrix[t][l + i], + matrix[t + i][r], + matrix[b][r - i] + ] + + l += 1 + r -= 1 + t += 1 + b -= 1 diff --git a/subtree-of-another-tree/Chaedie.py b/subtree-of-another-tree/Chaedie.py new file mode 100644 index 000000000..e3d4afd9c --- /dev/null +++ b/subtree-of-another-tree/Chaedie.py @@ -0,0 +1,25 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: + if not subRoot: return True + if not root: return False + + if self.sameTree(root, subRoot): + return True + + return (self.isSubtree(root.left, subRoot) or + self.isSubtree(root.right, subRoot)) + + def sameTree(self, s, t): + if not s and not t: + return True + + if s and t and s.val == t.val: + return (self.sameTree(s.left, t.left) and + self.sameTree(s.right, t.right)) + return False