MrainW's Home

All things come to those who wait!

0%

LeetCode 3. Longest Substring Without Repeating Characters

Question

Given a string s, find the length of the longest substring without repeating characters.

https://leetcode.com/problems/longest-substring-without-repeating-characters/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int left = 0, res = 0;
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//左指针将重复元素移除
while (!set.add(c)) set.remove(s.charAt(left++));
res = Math.max(res, i - left + 1);
}
return res;
}
}

Complexity:

Time complexity: O( n)

Space complexity: O(1)

Welcome to my other publishing channels