Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf96ce6e

Browse files
committed
feat: add leetcode-03.
1 parent0c99dbb commitf96ce6e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
packagecom.yeahqing.medium._003;
2+
3+
importjava.util.HashSet;
4+
5+
/**
6+
* @author YeahQing
7+
* @date 2022/10/1
8+
*/
9+
classSolution {
10+
/***
11+
* 3. 无重复字符的最长子串
12+
* 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
13+
* @param s 字符串s
14+
* @return 无重复字符的最长子串的长度
15+
*/
16+
publicintlengthOfLongestSubstring(Strings) {
17+
// 用数据结构HashSet集合,实现控制元素只能出现一次
18+
HashSet<Character>set =newHashSet<>();
19+
intj = -1,ans =0;
20+
intn =s.length();
21+
for (inti =0;i <n;i++) {
22+
if (i !=0) {
23+
// 移除集合中前一个元素, 因为判断的是i开始的子串
24+
set.remove(s.charAt(i-1));
25+
}
26+
// 从i+1到j可以保证没有重复的字符, 因此不需要每次重置j的位置
27+
while (j+1 <n && !set.contains(s.charAt(j+1))) {
28+
// 如果集合中没有这个字符,就把它加入到集合中
29+
set.add(s.charAt(j+1));
30+
j++;
31+
}
32+
// 当前集合的长度就是当前子串中不重复的最大子串长度
33+
// j - i + 1
34+
ans =Math.max(ans,set.size());
35+
}
36+
returnans;
37+
}
38+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp