Longest Substring Without Repeating Characters
问题描述
Given a string, find the length of the longest substring without repeating characters.
示例
- Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
- Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
- Example 3:
Input: “pwwkew”
Output: 3
Explanation: 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.
算法思路
该问题可以简化成查找一个字符串中最长的不重复字符子串,返回子串的长度。第一种方法用到了枚举和字典,感觉有点绕,我没有理解清楚;第二种方法采用了字符串的split方法,很巧妙,不过比较难想到。两种方法相比,第二种方法运行时间更短(84ms < 88ms),推荐使用第二种方法,感兴趣的朋友可以研究下第一种方法。
方法一:
1 |
|
方法二:
1 |
|
参考资料
- https://www.w3schools.com/python/ref_string_split.asp Python String split() Method
- https://leetcode.com/problems/longest-substring-without-repeating-characters/ longest-substring-without-repeating-characters
Longest Substring Without Repeating Characters
https://xiepeng21.cn/posts/8e8877f3/