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.
求最长子字符串的长度,注意是连续的子字符串。双指针维护一个动态窗口,遍历一个长度即可,时间复杂度O(n),用一个hashSet判断动态窗口中是否能加上,即字母是否重复,遍历一圈后记录最大的窗口长度。
看了讨论区的代码,思路是一样的,只不过用的是hashMap记录是否重复,看起来简洁一些
代码:
class Solution {
public int lengthOfLongestSubstring(String s) {
int left = 0, right = 0, max = 0;
if (s == null || s.length() == 0) {
return 0;
}
Set<Character> set = new HashSet<>();
while (right < s.length()) {
//能添加上 没有重复,右指针走一个
while (right < s.length() && set.add(s.charAt(right))) {
right++;
}
max = Math.max(max, right - left);
set.remove(s.charAt(left));
//有重复的话向左移,直到重复字符被剔除 移动到了下一个字母位置
left++;
}
return max;
}
}