LeetCode 第三题 无重复字符串的字符子串
题目:
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
思路:
遍历字符串,如果当前遍历到的字母没有在数组中,就把这个字母加入到数组中,并且要使得需要返回的最长子字符串长度maxLength = len(arr)
等于数组的最大长度。当遍历到数组中已经有过该字母的时候,就把数组中从开始到相同字母的位置全都删掉。
举个例子:abcabcbb
从下面的表格中可以看出,当到达第7轮的时候,数组中的字母就变成cb了,长度减小了,但是maxLength不变,所以可以保存到最长的子串长度。
循环轮次 | 列表内容 | maxLength |
---|---|---|
1 | a | 1 |
2 | ab | 2 |
3 | abc | 3 |
4 | bca | 3 |
5 | cab | 3 |
6 | abc | 3 |
7 | cb | 3 |
8 | b | 3 |
代码:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# 因为最大长度可能会减少,我们需要保留最大长度作为中间量这点很重要
arr = []
maxLenth = 0
for index,item in enumerate(s):
if item in arr:
currentIndex = arr.index(item)
arr.append(item)
arr = arr[currentIndex + 1:]
if item not in arr:
arr.append(item)
if len(arr) > maxLenth:
maxLenth = len(arr)
return maxLenth