题目
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
示例 4:
输入: s = ""
输出: 0
思路:使用滑动窗口方法。
分析,如果递增开始字符串的位置,那么结束的字符串位置也是递增的,这时就可以采用滑动窗口思路。利用hashset去重原理,如果发现末尾的元素存在set集合中,则当前开始索引的最长串已经找到,移除set中头元素,同时头元素索引后移。
package Leecode;
import java.util.HashSet;
public class test002 {
public static void main(String[] args) {
String s = "pwwkew";
int i = lengthOfLongestSubstring(s);
char[] chars = s.toCharArray();
System.out.println(i);
}
public static int lengthOfLongestSubstring(String s) {
int end = -1, count = 0;
HashSet<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (i != 0) {
set.remove(s.charAt(i - 1));
}
while (end + 1 < s.length() && !set.contains(s.charAt(end + 1))) {
set.add(s.charAt(end + 1));
end++;
}
count = Math.max(count, end - i + 1);
}
return count;
}
}