LeetCode03-无重复字符的最长子串(Python3)

文章目录

题目

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters

示例

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
----------------------------------------------------------------
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
----------------------------------------------------------------
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

求解

基本思路: 如果输入字符串没有重复,返回该字符串长度,如果输入字符串有重复字符,从输入字符串的首字符开始遍历,发现重复字符就从该字符的第一次出现位置重新开始遍历,以此类推,直到无重复字符,返回长度。python中自带的index函数是返回要查找字符的索引(如果有多个只返回第一个)。

class Solution(object):
	def lengthOfLongestSubstring(self, s: str) -> int:
		stringlenth = len(s)
		inputString = list(s)
		Dict = []
		N = []
		while inputString != []:
			sPreString = inputString.pop()
			if sPreString in Dict:
				Index = Dict.index(sPreString) + 1
				del Dict[0:Index]
				Dict.append(sPreString)
			else:
				Dict.append(sPreString)
				length = len(Dict)
				N.append(length)
		if N == []:
			return stringlenth
		else:	
			stringlenth = max(N)
		return stringlenth


if __name__ == '__main__':
	s = input("input a string:\n")
	solution = Solution()
	length = solution.lengthOfLongestSubstring(s)
	print(length)

该问题还有一个更精炼的解法,不过时间复杂度和上面我写的差不多,其实我感觉下面这个应该更快一点。(测试了一下python遍历字符串和遍历列表用时差不多,大体思路一致的情况下,我的语句多,应该耗时更多)

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        res = 0;i = 0
        for j in range(len(s)):
            if s[j] not in s[i:j]:
                res = max(res,j+1-i)
            else:
                i += s[i:j].index(s[j]) + 1
        return res
发布了46 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/l_changyun/article/details/94143235