写一个代码:Given a string s, find the length of the longest substring without repeating characters.
时间: 2023-03-07 16:50:58 浏览: 155
答案:int lengthOfLongestSubstring(string s) {
int len = 0;
int start = 0;
int end = 0;
unordered_set<char> seen;
while (end < s.length()) {
if (seen.find(s[end]) == seen.end()) {
seen.insert(s[end]);
end++;
len = max(len, end - start);
}
else {
seen.erase(s[start]);
start++;
}
}
return len;
}
相关问题
Given a string s, find the length of the longest substring without repeating characters.
To find the length of the longest substring without repeating characters, we can use the sliding window approach. Here's the algorithm:
1. Initialize a set to store the unique characters in the current window, and two pointers left and right to mark the current window.
2. Initialize a variable max_len to 0 to store the length of the longest substring without repeating characters.
3. While the right pointer is less than the length of the string s:
- If the character at s[right] is not in the set, add it to the set and move the right pointer to the right.
- Else, remove the character at s[left] from the set and move the left pointer to the right.
4. Update the value of max_len with the maximum of its current value and the size of the set.
5. Return max_len.
Here's the Python code for the algorithm:
```
def longest_substring(s):
unique_chars = set()
left = 0
max_len = 0
for right in range(len(s)):
while s[right] in unique_chars:
unique_chars.remove(s[left])
left += 1
unique_chars.add(s[right])
max_len = max(max_len, len(unique_chars))
return max_len
```
Example usage:
```
s = "abcabcbb"
print(longest_substring(s)) # Output: 3 (for "abc")
```
Given a string, find the longest substring without repeating characters. Examples: Given “abcabcbb”, the answer is “abc”, which the length is 3. Given “bbbbb”, the answer is “b”, with the length of 1. Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring. 输入 a sevral lines of string. 输出 the longest substring without repeating characters for each given string. 样例输入 Copy abcabcbb bbbbb pwwkew 样例输出 Copy abc b wke
给定一串字符串,寻找它们中不含有重复字符的最长子串。例如:给定“abcabcbb”,答案是“abc”,长度为3;给定“bbbbb”,答案是“b”,长度为1;给定“pwwkew”,答案是“wke”,长度为3(注意,答案必须是子串,“pwke”是子序列而不是子串)。输入:一行或多行字符串;输出:每个给定字符串的不含有重复字符的最长子串。
阅读全文