File tree Expand file tree Collapse file tree 5 files changed +214
-6
lines changed
longest-substring-without-repeating-characters Expand file tree Collapse file tree 5 files changed +214
-6
lines changed Original file line number Diff line number Diff line change @@ -58,3 +58,29 @@ def lengthOfLongestSubstring(self, s: str) -> int:
58
58
max_len = max (max_len , right - left + 1 )
59
59
60
60
return max_len
61
+
62
+
63
+ # HashMap 풀이
64
+ def lengthOfLongestSubstring (s : str ) -> int :
65
+ if not s :
66
+ return 0
67
+
68
+ left = 0 # 윈도우 시작점
69
+ max_length = 0 # 최대 길이
70
+ seen = {} # 문자의 마지막 등장 위치를 저장하는 해시맵
71
+
72
+ for right in range (len (s )):
73
+ char = s [right ]
74
+
75
+ # 현재 문자가 윈도우 내에 이미 존재하는 경우
76
+ if char in seen and seen [char ] >= left :
77
+ # 윈도우 시작점을 중복 문자 다음 위치로 이동
78
+ left = seen [char ] + 1
79
+
80
+ # 현재 문자의 위치 업데이트
81
+ seen [char ] = right
82
+
83
+ # 현재 윈도우 길이와 최대 길이 비교 후 업데이트
84
+ max_length = max (max_length , right - left + 1 )
85
+
86
+ return max_length
Original file line number Diff line number Diff line change
1
+ """
2
+ https://leetcode.com/problems/number-of-islands/
3
+
4
+ Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
5
+
6
+ An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
7
+
8
+
9
+ Example 1:
10
+ Input: grid = [
11
+ ["1","1","1","1","0"],
12
+ ["1","1","0","1","0"],
13
+ ["1","1","0","0","0"],
14
+ ["0","0","0","0","0"]
15
+ ]
16
+ Output: 1
17
+
18
+ Example 2:
19
+ Input: grid = [
20
+ ["1","1","0","0","0"],
21
+ ["1","1","0","0","0"],
22
+ ["0","0","1","0","0"],
23
+ ["0","0","0","1","1"]
24
+ ]
25
+ Output: 3
26
+
27
+ Constraints:
28
+ m == grid.length
29
+ n == grid[i].length
30
+ 1 <= m, n <= 300
31
+ grid[i][j] is '0' or '1'.
32
+
33
+ BFS 풀이
34
+ TC: O(m * n)
35
+ SC: O(m * n)
36
+ """
37
+
38
+ from collections import deque
39
+ from typing import List
40
+
41
+ class Solution :
42
+ def numIslands (self , grid : List [List [str ]]) -> int :
43
+ ans = 0
44
+ dx = [- 1 , 1 , 0 , 0 ]
45
+ dy = [0 , 0 , - 1 , 1 ]
46
+ rows = len (grid )
47
+ cols = len (grid [0 ])
48
+
49
+ def bfs (x , y ):
50
+ queue = deque ()
51
+ queue .append ((x , y ))
52
+ grid [x ][y ] = 2
53
+
54
+ while queue :
55
+ x , y = queue .popleft ()
56
+ for i in range (4 ):
57
+ nx = x + dx [i ]
58
+ ny = y + dy [i ]
59
+ if 0 <= nx < rows and 0 <= ny < cols :
60
+ if grid [nx ][ny ] == "1" :
61
+ grid [nx ][ny ] = "2"
62
+ queue .append ((nx , ny ))
63
+
64
+ return True
65
+
66
+ for i in range (rows ):
67
+ for j in range (cols ):
68
+ if grid [i ][j ] == "1" :
69
+ if bfs (i , j ):
70
+ ans += 1
71
+
72
+ return ans
Original file line number Diff line number Diff line change 1
- # Definition for singly-linked list.
2
- # class ListNode:
3
- # def __init__(self, val=0, next=None):
4
- # self.val = val
5
- # self.next = next
6
-
7
1
"""
2
+ https://leetcode.com/problems/reverse-linked-list/
3
+
8
4
1. Stack 활용 (LIFO)
9
5
- LinkedList의 모든 원소를 Stack에 넣고 꺼냄
10
6
TC: O(n) time
16
12
SC: O(1) -> 변수를 포인터 2개만 사용
17
13
"""
18
14
15
+ # Definition for singly-linked list.
16
+ class ListNode :
17
+ def __init__ (self , val = 0 , next = None ):
18
+ self .val = val
19
+ self .next = next
20
+
19
21
# Stack 풀이
20
22
class Solution :
21
23
def reverseList (self , head : Optional [ListNode ]) -> Optional [ListNode ]:
@@ -42,3 +44,27 @@ def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
42
44
curr .next = prev
43
45
prev , curr = curr , temp_next
44
46
return prev
47
+
48
+
49
+ """
50
+ 25/9/5 복습
51
+
52
+ 링크드 리스트 뒤집기
53
+ => 노드를 옮기는 것이 아니라, next 포인터의 방향을 바꾸면 된다!
54
+
55
+ TC: O(n)
56
+ SC: O(1)
57
+ """
58
+ class Solution :
59
+ def reverseList (self , head : Optional [ListNode ]) -> Optional [ListNode ]:
60
+ prev = None # 이전 노드
61
+ curr = head # 현재 노드
62
+
63
+ while curr :
64
+ next_node = curr .next # 다음 노드 기억
65
+ curr .next = prev # 현재 노드의 방향을 반대로
66
+ prev = curr # 이전 노드를 한 칸 앞으로
67
+ curr = next_node # 현재 노드를 다음으로 이동
68
+
69
+ # prev가 마지막 노드이자 새 head
70
+ return prev
Original file line number Diff line number Diff line change
1
+ """
2
+ https://leetcode.com/problems/set-matrix-zeroes/description/
3
+
4
+ Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
5
+ You must do it in place.
6
+
7
+ TC: O(m * n)
8
+ SC: O(m + n), set 자료구조 사용
9
+ """
10
+
11
+ class Solution :
12
+ def setZeroes (self , matrix : List [List [int ]]) -> None :
13
+ """
14
+ Do not return anything, modify matrix in-place instead.
15
+ """
16
+ rows = len (matrix )
17
+ cols = len (matrix [0 ])
18
+
19
+ zero_rows = set () # 최대 m개의 행 인덱스 저장
20
+ zero_cols = set () # 최대 n개의 열 인덱스 저장
21
+
22
+ # 0이 있는 위치 찾기
23
+ for i in range (rows ):
24
+ for j in range (cols ):
25
+ if matrix [i ][j ] == 0 :
26
+ zero_rows .add (i )
27
+ zero_cols .add (j )
28
+
29
+ # 0이 있는 행과 열 모두 0으로 만들기
30
+ for i in range (rows ):
31
+ for j in range (cols ):
32
+ if i in zero_rows or j in zero_cols :
33
+ matrix [i ][j ] = 0
Original file line number Diff line number Diff line change
1
+ """
2
+ https://leetcode.com/problems/unique-paths/description/
3
+
4
+ 아래로 이동 혹은 (1, 0)
5
+ 오른쪽 이동만 가능 (0, 1)
6
+
7
+ m => rows, n = cols
8
+ 로봇이 (0, 0)에서 (m-1, n-1)에 도착 가능한 unique paths 개수를 반환
9
+
10
+ 풀이 시간: 16분
11
+ 처음에 어떻게 풀어야 할 줄 몰랐지만, 그림을 그려보며 누적 규칙을 찾음 (위, 왼쪽 값 더해나가기)
12
+ paths[i][j] = paths[i-1][j] + paths[i][j-1]
13
+
14
+ TC: O(m * n)
15
+ SC: O(m * n)
16
+ """
17
+
18
+ class Solution :
19
+ def uniquePaths (self , m : int , n : int ) -> int :
20
+ paths = [[0 ] * n for _ in range (m )]
21
+ paths [0 ][0 ] = 1
22
+
23
+ for i in range (m ):
24
+ for j in range (n ):
25
+ if i - 1 >= 0 and j - 1 >= 0 :
26
+ paths [i ][j ] = paths [i - 1 ][j ] + paths [i ][j - 1 ]
27
+ else :
28
+ paths [i ][j ] = 1
29
+
30
+ return paths [m - 1 ][n - 1 ]
31
+
32
+
33
+ """
34
+ 공간 복잡도 최적화 풀이 - 복습 필요
35
+ dp[i][j] = dp[i-1][j] + dp[i][j-1]
36
+ => dp[j] = dp[j] + dp[j-1]
37
+
38
+ TC: O(m * n)
39
+ SC: O(n)
40
+ """
41
+
42
+ class Solution :
43
+ def uniquePaths (self , m : int , n : int ) -> int :
44
+ # 첫 행은 모두 1로 초기화
45
+ dp = [1 ] * n
46
+
47
+ for i in range (1 , m ):
48
+ for j in range (1 , n ):
49
+ dp [j ] = dp [j ] + dp [j - 1 ]
50
+
51
+ return dp [- 1 ]
You can’t perform that action at this time.
0 commit comments