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

题目链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

java 代码

执行用时:2 ms, 在所有 Java 提交中击败了95.98% 的用户
内存消耗:41.4 MB, 在所有 Java 提交中击败了5.02% 的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 1) { return 1;}
int cursor, end = 1, length = s.length();
int beginAgain = 0, longest = 0;
while (end < length) {
cursor = beginAgain;
while (cursor < end) {
if (s.charAt(cursor) == s.charAt(end)) {
beginAgain = cursor + 1;
break;
}
cursor++;
}
longest = Math.max(longest, end - beginAgain + 1);
end++;
}
return longest;
}
}

swift 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
if s.isEmpty { return 0}
let length = s.count
var count = 0
var str = Array(s)
var cursor = 0, end = 0, beginAgain = 0
while end < length {
cursor = beginAgain
while cursor < end {
if str[cursor] == str[end] {
beginAgain = cursor + 1
break
}
cursor += 1
}
count = max(count, end - beginAgain + 1)
end += 1
}
return count
}
}


3. 无重复字符的最长子串
https://pisces34.github.io/2022/01/25/leetcode/3/
发布于
2022年1月25日
许可协议