Longest Substring Without Repeating Characters
欢迎访问 我的个人博客
- Difficulty: Medium
Description
Given a string, find the length of the longest substring without repeating characters.
Examples
Given
"abcabcbb"
, the answer is"abc"
, which the length is 3.
Given"bbbbb"
, the answer is"b"
, with the length of 1.
Given"pwwkew"
, 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.
Thinking
- 返回字符串中的最长不重复子串的长度
Solution -1
- 32ms, beats 99.27%
- 自己的做法,有点暴力
- list 中存放不重复的子串,一旦当前字符 list 中存在,就不断的剔除子串的首个字符,直到剔除相同字符后
public static int lengthOfLongestSubstring(String s) {
List<Character> list = new LinkedList<>();
int result = 0;
for (int i = 0; i < s.length(); i++) {
char temp = s.charAt(i);
if (list.contains(temp)) {
while (list.contains(temp)) {
list.remove(0);
}
}
list.add(temp);
result = Math.max(result, list.size());
}
return result;
}
Solution -2
- 22ms, beats 99.99%
- Leetcode 大神解法
- 滑动窗口思想:如果当前遇到的字符 j 同字符 i 相同,那么当前的不重复子串长度等于 length = j-i+1
public static int lengthOfLongestSubstring(String s) {
int[] flag = new int[128];
int result = 0;
for (int i = 0, j = 0; j < s.length(); j++) {
i = Math.max(flag[s.charAt(j)], i);
result = Math.max(result, j-i+1);
flag[s.charAt(j)] = j+1;
}
return result;
}