3

#yyds干货盘点# LeetCode 热题 HOT 100:无重复字符的最长子串

 2 years ago
source link: https://blog.51cto.com/u_13321676/5666626
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# LeetCode 热题 HOT 100:无重复字符的最长子串

精选 原创

灰太狼_cxh 2022-09-09 17:55:08 博主文章分类:leetcode ©著作权

文章标签 最长子串 子串 字符串 文章分类 Java 编程语言 阅读数341

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

输入: s = "abcabcbb"

解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

输入: s = "bbbbb"

解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

输入: s = "pwwkew"

解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。

    请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

代码实现:

class Solution {
public int lengthOfLongestSubstring(String s) {
// 哈希集合,记录每个字符是否出现过
Set<Character> occ = new HashSet<Character>();
int n = s.length();
// 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动
int rk = -1, ans = 0;
for (int i = 0; i < n; ++i) {
if (i != 0) {
// 左指针向右移动一格,移除一个字符
occ.remove(s.charAt(i - 1));
}
while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
// 不断地移动右指针
occ.add(s.charAt(rk + 1));
++rk;
}
// 第 i 到 rk 个字符是一个极长的无重复字符子串
ans = Math.max(ans, rk - i + 1);
}
return ans;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK