comments | edit_url |
---|---|
true |
给定一个字符串 s
,请你找出其中不含有重复字符的 最长连续子字符串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子字符串是 "abc",所以其
长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子字符串是 "b"
,所以其长度为 1。
示例 3:
输入: s = "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是"wke"
,所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke"
是一个子序列,不是子串。
示例 4:
输入: s = "" 输出: 0
提示:
0 <= s.length <= 5 * 104
s
由英文字母、数字、符号和空格组成
注意:本题与主站 3 题相同: https://leetcode.cn/problems/longest-substring-without-repeating-characters/
我们用两个指针
接下来,我们遍历字符串 false
,此时
时间复杂度
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
ss = set()
ans = j = 0
for i, c in enumerate(s):
while c in ss:
ss.remove(s[j])
j += 1
ans = max(ans, i - j + 1)
ss.add(c)
return ans
class Solution {
public int lengthOfLongestSubstring(String s) {
boolean[] ss = new boolean[128];
int ans = 0, j = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
char c = s.charAt(i);
while (ss[c]) {
ss[s.charAt(j++)] = false;
}
ans = Math.max(ans, i - j + 1);
ss[c] = true;
}
return ans;
}
}
class Solution {
public:
int lengthOfLongestSubstring(string s) {
bool ss[128] = {false};
int n = s.size();
int ans = 0;
for (int i = 0, j = 0; i < n; ++i) {
while (ss[s[i]]) {
ss[s[j++]] = false;
}
ss[s[i]] = true;
ans = max(ans, i - j + 1);
}
return ans;
}
};
func lengthOfLongestSubstring(s string) (ans int) {
ss := make([]bool, 128)
j := 0
for i, c := range s {
for ss[c] {
ss[s[j]] = false
j++
}
ss[c] = true
ans = max(ans, i-j+1)
}
return
}
function lengthOfLongestSubstring(s: string): number {
let ans = 0;
const vis = new Set<string>();
for (let i = 0, j = 0; i < s.length; ++i) {
while (vis.has(s[i])) {
vis.delete(s[j++]);
}
vis.add(s[i]);
ans = Math.max(ans, i - j + 1);
}
return ans;
}
function lengthOfLongestSubstring(s: string): number {
let ans = 0;
const n = s.length;
const ss: boolean[] = new Array(128).fill(false);
for (let i = 0, j = 0; i < n; ++i) {
while (ss[s[i]]) {
ss[s[j++]] = false;
}
ss[s[i]] = true;
ans = Math.max(ans, i - j + 1);
}
return ans;
}
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
var ss = Array(repeating: false, count: 128)
var ans = 0
var j = s.startIndex
for i in s.indices {
let c = s[i]
while ss[Int(c.asciiValue!)] {
ss[Int(s[j].asciiValue!)] = false
j = s.index(after: j)
}
ans = max(ans, s.distance(from: j, to: i) + 1)
ss[Int(c.asciiValue!)] = true
}
return ans
}
}