|
| 1 | +/** |
| 2 | + * [Problem]: [3] Longest Substring Without Repeating Characters |
| 3 | + * (https://leetcode.com/problems/longest-substring-without-repeating-characters/description/) |
| 4 | + */ |
| 5 | + |
| 6 | +/* |
| 7 | + * 1. 중복없이 이어는 문자열 중 가장 긴 문자열 |
| 8 | + */ |
| 9 | +function lengthOfLongestSubstring(s: string): number { |
| 10 | + // 시간 복잡도: O(n^2) |
| 11 | + // 공간 복잡도: O(n) |
| 12 | + function bruteForceFunc(s: string): number { |
| 13 | + let max = 0; |
| 14 | + for (let i = 0; i < s.length; i++) { |
| 15 | + const duplicate = new Set<string>(); |
| 16 | + let j = i; |
| 17 | + let count = 0; |
| 18 | + |
| 19 | + while (j < s.length && !duplicate.has(s[j])) { |
| 20 | + duplicate.add(s[j]); |
| 21 | + count++; |
| 22 | + j++; |
| 23 | + } |
| 24 | + |
| 25 | + max = Math.max(max, count); |
| 26 | + } |
| 27 | + |
| 28 | + return max; |
| 29 | + } |
| 30 | + //시간복잡도 O(n) |
| 31 | + //공간복잡도 O(n) |
| 32 | + function slidingWindowFunc(s: string): number { |
| 33 | + let left = 0; |
| 34 | + let right = 0; |
| 35 | + let window = new Set<string>(); |
| 36 | + let max = 0; |
| 37 | + while (right < s.length) { |
| 38 | + if (window.has(s[right])) { |
| 39 | + window.delete(s[left]); |
| 40 | + left++; |
| 41 | + } else { |
| 42 | + window.add(s[right]); |
| 43 | + max = Math.max(max, right - left + 1); |
| 44 | + right++; |
| 45 | + } |
| 46 | + // while (window.has(s[right])) { |
| 47 | + // window.delete(s[left]); |
| 48 | + // left++; |
| 49 | + // } |
| 50 | + |
| 51 | + // window.add(s[right]); |
| 52 | + // max = Math.max(max, right - left + 1); |
| 53 | + // right++; |
| 54 | + } |
| 55 | + |
| 56 | + return max; |
| 57 | + } |
| 58 | + |
| 59 | + //시간복잡도 O(n) |
| 60 | + //공간복잡도 O(n) |
| 61 | + //set에서 left 인덱스를 조금 더 빠르게 가져올 수 있음 |
| 62 | + function mapFunc(s: string): number { |
| 63 | + let left = 0; |
| 64 | + let max = 0; |
| 65 | + let map = new Map<string, number>(); |
| 66 | + |
| 67 | + for (let right = 0; right < s.length; right++) { |
| 68 | + if (map.has(s[right])) { |
| 69 | + left = Math.max(left, map.get(s[right])! + 1); |
| 70 | + } |
| 71 | + |
| 72 | + map.set(s[right], right); |
| 73 | + max = Math.max(max, right - left + 1); |
| 74 | + } |
| 75 | + |
| 76 | + return max; |
| 77 | + } |
| 78 | + |
| 79 | + return mapFunc(s); |
| 80 | +} |
0 commit comments