0
点赞
收藏
分享

微信扫一扫

leetcode-3.无重复字符的最长子串


给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:

输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:

输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。

/**
* 无重复字符的最长子串:<a href="https://leetcode.cn/problems/longest-substring-without-repeating-characters/">https://leetcode.cn/problems/longest-substring-without-repeating-characters/</a>
*
* @author Felix
* @Date 2022/7/13 21:00
* @since 1.0.0
**/
public class L3无重复字符的最长子串 {
/**
* 给定一个字符串 s ,请你找出其中不含有重复字符的最长子串的长度。
* <p>
* <p>
* <p>
* 示例1:
* <p>
* 输入: s = "abcabcbb"
* 输出: 3
* 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
* 示例 2:
* <p>
* 输入: s = "bbbbb"
* 输出: 1
* 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
* 示例 3:
* <p>
* 输入: s = "pwwkew"
* 输出: 3
* 解释: 因为无重复字符的最长子串是"wke",所以其长度为 3。
* 请注意,你的答案必须是 子串 的长度,"pwke"是一个子序列,不是子串。
* <p>
* 链接:<a href="https://leetcode.cn/problems/longest-substring-without-repeating-characters">https://leetcode.cn/problems/longest-substring-without-repeating-characters</a>
*/

/**
* 滑动窗口思想,借助官方提醒.
* eg. pwwkwe
* 往set集合里面放入,并且移动窗口的起始位置:repeatIndex.
* 每次判断到有一个重复的字符,就把这个字符前的所有字符删除,就是删除[repeatIndex,i)范围的,重新
* 找一个新的不重复的串,存入set,根据set的size找出最长的长度
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String str = null;
while ((str = bufferedReader.readLine()) != null) {
char[] chars = str.toCharArray();
Set<Character> set = new HashSet<>();
int repeatIndex = 0;
int length = 0;
for (int i = 0; i < chars.length; i++) {
if (set.contains(chars[i])) {
for (int j = repeatIndex; j < i; j++) {
set.remove(chars[j]);
if (chars[i] == chars[j]) {
repeatIndex = j + 1;
break;
}
}
}
set.add(chars[i]);
if (set.size() > length) {
length = set.size();
}
}
System.out.println(length);
}

}
}


举报

相关推荐

0 条评论