Algorithm
[Leetcode] 3번 - Longest Substring Without Repeating Characters (Java, Kotlin)
2020. 3. 28. 18:24반응형
3. Longest Substring Without Repeating Characters (Medium)
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
Java Solution
import java.util.*;
class Solution {
public int lengthOfLongestSubstring(String s) {
Set set = new HashSet();
int n = s.length();
int begin = 0, end = 0;
int ans = 0;
while(end < n) {
if(set.contains(s.charAt(end))) {
set.remove(s.charAt(begin++));
} else {
set.add(s.charAt(end++));
ans = Math.max(ans, end - begin);
}
}
return ans;
}
}
Kotlin Solution
class Solution {
fun lengthOfLongestSubstring(s: String): Int {
val set = hashSetOf<Char>()
val n = s.length
var begin = 0
var end = 0
var answer = 0
while (end < n) {
if (s[end] in set) {
set.remove(s[begin++])
} else {
set.add(s[end++])
answer = Integer.max(answer, end - begin)
}
}
return answer
}
}
이 외에도 다양한 문제들의 해답 코드를 깃헙 저장소에서 확인할 수 있습니다. (Java, Kotlin)
반응형
'Algorithm' 카테고리의 다른 글
[Leetcode] 4번 - Median of Two Sorted Arrays (Java, Kotlin) (0) | 2020.03.29 |
---|---|
[Leetcode] 2번 - Add Two Numbers (Java, Kotlin) (0) | 2020.03.27 |
[LeetCode] 1번 - Two Sum (Java, Kotlin) (0) | 2020.03.26 |
알고리즘 사이트 비교 및 추천 (4) | 2019.11.10 |
[백 트래킹][백준 1948번] N과 M(1) - Java (0) | 2019.10.03 |