更新 test.java

master
wangsiyuan 2023-09-05 15:57:36 +08:00
parent 262525db57
commit 955e0e3d05
1 changed files with 1 additions and 29 deletions

View File

@ -6,34 +6,6 @@ import java.util.Set;
public class test {
public static void main(String[] args) {
String s = "bbbbb";
String s1 = "abcabcbb";
String s2 = "pwwkew";
String s3 = "ckilbkd";
String s4 = "dvdf";
System.out.println(lengthOfLongestSubstring(s3));
}
public static 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;
}
}