leetCode:无重复字符的最长子串:
题目:
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
示例 4:
输入: s = “”
输出: 0
提示:
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
思路:
使用HashSet作为滑动窗口,start与end分别指向子串开始与结尾,当end对应的字符存在的时候则移除HashSet中start位置对应的字符,当end对应的字符不存在的时候则向HashSet中添加end位置对应的字符。
代码:
class Solution {
//使用set滚动窗口
public int lengthOfLongestSubstring(String s) {
if (s.equals("")) {
return 0;
}
if (!isRepeat(s)) {
return s.length();
}
Set<Character> set = new HashSet<>();
int start = 0;
int end = 0;
int num = 0;
int n = s.length();
while (start < n && end < n) {
if (!set.contains(s.charAt(end))) {
set.add(s.charAt(end++));
num = Math.max(num, end - start);
} else {
set.remove(s.charAt(start++));
}
}
return num;
}
/**
* 判断这个字符串是否含有重复字符
*
* @param str 目标字符串
* @return true 有重复的;false 没有重复的。
*/
public boolean isRepeat(String str) {
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
return true;
}
}
}
return false;
}
}