File tree Expand file tree Collapse file tree 3 files changed +97
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 3 files changed +97
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Solution:
3+ 1) 포문을 돌면서 좌우 투포인터로 벌려주며 같은 문자인지 확인한다. 같으면 팰린드롬, 아니면 break
4+ 2) 홀수, 짝수를 별도로 순회한다.
5+
6+ Time: O(n^2)
7+ Space: O(1)
8+ """
9+
10+ class Solution :
11+ def longestPalindrome (self , s : str ) -> str :
12+ result = s [0 ]
13+
14+ for i in range (len (s )):
15+ # check odd
16+ word = s [i ]
17+ left , right = i - 1 , i + 1
18+ while left >= 0 and right < len (s ):
19+ if s [left ] == s [right ]:
20+ word = s [left ] + word + s [right ]
21+ if len (result ) < len (word ):
22+ result = word
23+ left -= 1
24+ right += 1
25+ else :
26+ break
27+
28+ word = ""
29+ left , right = i , i + 1
30+ while left >= 0 and right < len (s ):
31+ if s [left ] == s [right ]:
32+ word = s [left ] + word + s [right ]
33+ if len (result ) < len (word ):
34+ result = word
35+ left -= 1
36+ right += 1
37+ else :
38+ break
39+
40+ return result
Original file line number Diff line number Diff line change 1+ """
2+ Solution: 1) 가장 바깥에서부터 안쪽으로 들어오며 4 원소의 자리를 바꿔준다.
3+ Time: O(n^2)
4+ Space: O(1)
5+ """
6+
7+
8+ class Solution :
9+ def rotate (self , matrix : List [List [int ]]) -> None :
10+ ROWS , COLS = len (matrix ), len (matrix [0 ])
11+
12+
13+ l , r = 0 , COLS - 1
14+ t , b = 0 , ROWS - 1
15+ while l < r and t < b :
16+ for i in range (r - l ):
17+ [
18+ matrix [t ][l + i ],
19+ matrix [t + i ][r ],
20+ matrix [b ][r - i ],
21+ matrix [b - i ][l ]
22+ ] = [
23+ matrix [b - i ][l ],
24+ matrix [t ][l + i ],
25+ matrix [t + i ][r ],
26+ matrix [b ][r - i ]
27+ ]
28+
29+ l += 1
30+ r -= 1
31+ t += 1
32+ b -= 1
Original file line number Diff line number Diff line change 1+ # Definition for a binary tree node.
2+ # class TreeNode:
3+ # def __init__(self, val=0, left=None, right=None):
4+ # self.val = val
5+ # self.left = left
6+ # self.right = right
7+ class Solution :
8+ def isSubtree (self , root : Optional [TreeNode ], subRoot : Optional [TreeNode ]) -> bool :
9+ if not subRoot : return True
10+ if not root : return False
11+
12+ if self .sameTree (root , subRoot ):
13+ return True
14+
15+ return (self .isSubtree (root .left , subRoot ) or
16+ self .isSubtree (root .right , subRoot ))
17+
18+ def sameTree (self , s , t ):
19+ if not s and not t :
20+ return True
21+
22+ if s and t and s .val == t .val :
23+ return (self .sameTree (s .left , t .left ) and
24+ self .sameTree (s .right , t .right ))
25+ return False
You can’t perform that action at this time.
0 commit comments