LC 3 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
public int lengthOfLongestSubstring(String s)
边界检查 : s 如果是空 返回0
解题思路 利用HashSet 检测重复字符。用两个指针操作
public int lengthOfLongestSubstring(String s) {
int i = 0, j = 0, max = 0;
Set<Character> set = new HashSet<>();
while (j < s.length()) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++));
max = Math.max(max, set.size());
} else {
set.remove(s.charAt(i++));
}
}
return max;
}
Last updated
Was this helpful?