题目
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.
Example 4:
Input: " "
Output: 1
解法(参考官方解法)
1、暴力破解
代码
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] toChar = s.toCharArray();
List list = new ArrayList();
int maxlen = 0;
int len = 0;
for(int i = 0; i < toChar.length; i++) {
len = 0;
list.clear();
for(int j = i; j < toChar.length; j++) {
if(!list.contains(toChar[j])) {
list.add(toChar[j]);
len++;
} else {
break;
}
maxlen = (j-i+1) > maxlen ? (j-i+1) : maxlen;
}
}
return maxlen;
}
}
滑动窗口
暴力破解太慢了,可以考虑其他的解法
可以这样想,暴力破解是从第0至n,依次作为最长字符串的第一个字符去找最长字符串的。
s[i]到s[j]为一组不含重复字母的字符串,若不出现重复字符串则j滑动,若出现重复字符则i滑动,持续判断两个滑动之间窗口大小。
代码
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet();
int ret = 0;
int i = 0;
int j = 0;
while(i < n && j < n) {
if(! set.contains(s.charAt(j))) {
set.add(s.charAt(j));
j++;
ret = Math.max(ret, j - i);
}else {
set.remove(s.charAt(i));
i++;
}
}
return ret;
}
}
滑动窗口升级
写到这里其实可以发现了,滑动窗口的意义在于:在j不断向右滑动的过程中,遇到前方出现过的字符,需要更换i的位置,来确定初始位置。
[i,j]这个窗口中,不存在重复字符,此时出现s[j+1]与s[k] (i<k<j)一致,可以确定的是[i,j+1]之间,无论从哪一个位置开始,都只是[i,j]这个窗口部分,那么从k+1开始,才有可能获得更大的窗口。
那么如果在一次的滑动过程中,记录下每一个字符的最后出现位置,那么在更换i的位置时可以省略不需要的步骤,直接到达k+1。这里值得注意的是,找到了重复的j+1和k一致,k得在[i,j]之间才行。
上代码
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int ret = 0;
Map<Character, Integer> map = new HashMap<>();
for(int i=0, j=0; j < n; j++) {
if(map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)) , i);
}
ret = Math.max(ret, j-i+1);
map.put(s.charAt(j), j+1);
}
return ret;
}
}
主要参考了官方给出的解答,以上。