Skip to content

Commit

Permalink
update post
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-jonghoonpark committed Jun 3, 2024
1 parent 1810720 commit 672d6c9
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 1 deletion.
95 changes: 94 additions & 1 deletion _posts/2024-02-18-leetcode-3.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,22 @@
layout: post
title: (Leetcode) 3 - Longest Substring Without Repeating Characters
categories: [스터디-알고리즘]
tags: [파이썬, 알고리즘, python, algorithm, Leetcode, string, char, character]
tags:
[
파이썬,
알고리즘,
python,
algorithm,
Leetcode,
string,
char,
character,
자바,
java,
set,
hashset,
queue,
]
date: 2024-02-18 12:00:00 +0900
---

Expand Down Expand Up @@ -69,3 +84,81 @@ class Solution:
똑똑하게 접근한 것 같다.

temp를 통해 최대로 긴 문자열을 저장해두고, 동일한 글자가 나오면 앞에서 해당 글자를 제거하고 뒤에 해당 글자를 추가하는 방식을 택하였다.

## Java로 다시 풀어보기 (queue를 사용해서 풀기) (240603)

위 글을 보지 않고 자바로 다시 풀어봤다.

```java
public int lengthOfLongestSubstring(String s) {
if (s.isEmpty()) {
return 0;
}

Queue<Character> queue = new LinkedList<>();
int start = 0;
int end = 0;
int longest = 0;

while (pointer < s.length()) {
char _char = s.charAt(pointer);
while (queue.contains(_char)) {
queue.remove();
}
queue.add(_char);
longest = Math.max(longest, queue.size());
pointer++;
}

return longest;
}
```

### TC, SC

시간 복잡도는 O(n^2) 이고, 공간 복잡도는 O(n) 이다.

![retry result](/assets/images/2024-02-18-leetcode-3/retry-result.png)

아무래도 시간을 더 줄여줘야 할 것 같다.

## 좀 더 최적화 해보기

contains 에서 시간을 많이 뺏는것 같다는 생각이 들었다. (순회 탐색 하려면 O(n) 이니깐)

중복이 되면 안된다는 점에서 Set을 사용했다.

```java
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.isEmpty()) {
return 0;
}

Set<Character> set = new HashSet<>();
int pointer = 0;
int longest = 0;

while (pointer < s.length()) {
char _char = s.charAt(pointer);
while (set.contains(_char)) {
set.remove(s.charAt(pointer - set.size()));
}
set.add(_char);
longest = Math.max(longest, set.size());
pointer++;
}

return longest;
}
}
```

## TC, SC

시간 복잡도는 O(n) 이고, 공간 복잡도는 O(n) 이다.
내부 while이 그대로 있지만 O(n)으로 적은 이유는 hash set의 경우 search 하는데 드는 비용이 O(1) 이기 때문이다.

![final result](/assets/images/2024-02-18-leetcode-3/final-result.png)

결과적으로 시간이 많이 줄어들었다.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 672d6c9

Please sign in to comment.