|
2 | 2 | layout: post
|
3 | 3 | title: (Leetcode) 3 - Longest Substring Without Repeating Characters
|
4 | 4 | categories: [스터디-알고리즘]
|
5 |
| -tags: [파이썬, 알고리즘, python, algorithm, Leetcode, string, char, character] |
| 5 | +tags: |
| 6 | + [ |
| 7 | + 파이썬, |
| 8 | + 알고리즘, |
| 9 | + python, |
| 10 | + algorithm, |
| 11 | + Leetcode, |
| 12 | + string, |
| 13 | + char, |
| 14 | + character, |
| 15 | + 자바, |
| 16 | + java, |
| 17 | + set, |
| 18 | + hashset, |
| 19 | + queue, |
| 20 | + ] |
6 | 21 | date: 2024-02-18 12:00:00 +0900
|
7 | 22 | ---
|
8 | 23 |
|
@@ -69,3 +84,81 @@ class Solution:
|
69 | 84 | 똑똑하게 접근한 것 같다.
|
70 | 85 |
|
71 | 86 | temp를 통해 최대로 긴 문자열을 저장해두고, 동일한 글자가 나오면 앞에서 해당 글자를 제거하고 뒤에 해당 글자를 추가하는 방식을 택하였다.
|
| 87 | + |
| 88 | +## Java로 다시 풀어보기 (queue를 사용해서 풀기) (240603) |
| 89 | + |
| 90 | +위 글을 보지 않고 자바로 다시 풀어봤다. |
| 91 | + |
| 92 | +```java |
| 93 | +public int lengthOfLongestSubstring(String s) { |
| 94 | + if (s.isEmpty()) { |
| 95 | + return 0; |
| 96 | + } |
| 97 | + |
| 98 | + Queue<Character> queue = new LinkedList<>(); |
| 99 | + int start = 0; |
| 100 | + int end = 0; |
| 101 | + int longest = 0; |
| 102 | + |
| 103 | + while (pointer < s.length()) { |
| 104 | + char _char = s.charAt(pointer); |
| 105 | + while (queue.contains(_char)) { |
| 106 | + queue.remove(); |
| 107 | + } |
| 108 | + queue.add(_char); |
| 109 | + longest = Math.max(longest, queue.size()); |
| 110 | + pointer++; |
| 111 | + } |
| 112 | + |
| 113 | + return longest; |
| 114 | +} |
| 115 | +``` |
| 116 | + |
| 117 | +### TC, SC |
| 118 | + |
| 119 | +시간 복잡도는 O(n^2) 이고, 공간 복잡도는 O(n) 이다. |
| 120 | + |
| 121 | + |
| 122 | + |
| 123 | +아무래도 시간을 더 줄여줘야 할 것 같다. |
| 124 | + |
| 125 | +## 좀 더 최적화 해보기 |
| 126 | + |
| 127 | +contains 에서 시간을 많이 뺏는것 같다는 생각이 들었다. (순회 탐색 하려면 O(n) 이니깐) |
| 128 | + |
| 129 | +중복이 되면 안된다는 점에서 Set을 사용했다. |
| 130 | + |
| 131 | +```java |
| 132 | +class Solution { |
| 133 | + public int lengthOfLongestSubstring(String s) { |
| 134 | + if (s.isEmpty()) { |
| 135 | + return 0; |
| 136 | + } |
| 137 | + |
| 138 | + Set<Character> set = new HashSet<>(); |
| 139 | + int pointer = 0; |
| 140 | + int longest = 0; |
| 141 | + |
| 142 | + while (pointer < s.length()) { |
| 143 | + char _char = s.charAt(pointer); |
| 144 | + while (set.contains(_char)) { |
| 145 | + set.remove(s.charAt(pointer - set.size())); |
| 146 | + } |
| 147 | + set.add(_char); |
| 148 | + longest = Math.max(longest, set.size()); |
| 149 | + pointer++; |
| 150 | + } |
| 151 | + |
| 152 | + return longest; |
| 153 | + } |
| 154 | +} |
| 155 | +``` |
| 156 | + |
| 157 | +## TC, SC |
| 158 | + |
| 159 | +시간 복잡도는 O(n) 이고, 공간 복잡도는 O(n) 이다. |
| 160 | +내부 while이 그대로 있지만 O(n)으로 적은 이유는 hash set의 경우 search 하는데 드는 비용이 O(1) 이기 때문이다. |
| 161 | + |
| 162 | + |
| 163 | + |
| 164 | +결과적으로 시간이 많이 줄어들었다. |
0 commit comments