[LeetCode] 3. Longest Substring Without Repeating Characters (Java)
2022. 12. 28. 07:33ㆍ알고리즘/LeetCode
Description
Given a string s, find the length of the longest substring without repeating characters.
반복되는 문자가 없는 가장 긴 문자열의 길이를 구하라.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
- 0 <= s.length <= 5 * 104
- s consists of English letters, digits, symbols and spaces
Solution
public class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
int i=0, j=0;
int length = s.length();
HashSet<Character> set = new HashSet<>();
while (j < length) {
if(i > j){
break;
}
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
maxLength = Math.max(maxLength, j - i);
continue;
}
set.remove(s.charAt(i++));
}
return maxLength;
}
}
j번째 문자부터 반복되지 않는 문자열까지의 길이를 구하여 Math.max()로 가장 큰 값을 구한다.
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 5. Longest Palindromic Substring (Java) (0) | 2023.01.02 |
---|---|
[LeetCode] 4. Median of Two Sorted Arrays (Java) - O(log (m+n)) (0) | 2023.01.02 |
[LeetCode] 4. Median of Two Sorted Arrays (Java) (0) | 2022.12.30 |
[LeetCode] 2. Add Two Numbers (Java) (0) | 2022.12.28 |
[LeetCode] 1. Two Sum (Java) (0) | 2022.12.22 |