欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > leetcode3. Longest Substring Without Repeating Characters

leetcode3. Longest Substring Without Repeating Characters

2025/5/13 22:32:41 来源:https://blog.csdn.net/weixin_44245188/article/details/143403241  浏览:    关键词:leetcode3. Longest Substring Without Repeating Characters

Given a string s, find the length of the longest
substring
without repeating characters.

Example 1:

Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.

Example 2:

Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.

Example 3:

Input: s = “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.

Constraints:

0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.
class Solution:def lengthOfLongestSubstring(self, s: str) -> int:left = 0right = 0 res = 0while right<len(s):char = s[right] # 左闭右闭,因此直接上来就将right的char纳入窗口中while char in s[left:right]: # 判断新纳入的char是否与窗口之前的元素有重复left += 1                # 有就收缩窗口res = max(res, right-left+1) # 每部比较一下窗口长度与最值right += 1 # right始终前行保障窗口不断在滑动return res # 返回最值

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词