题目:
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
Python解答:
思路:在字符串的首位设置两个指针p1、p2,p2逐个右移,当遇到与首个字符相同的字符时停止,此时p1右移一位,重复此过程即可得到结果
代码如下:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
p1=0
p2=0
count=0
if len(s)==0:
return 0
if s.count(s[0])==len(s):
return 1
if len(set(s))==len(s):
return len(s)
while p2<len(s):
if s[p2] not in s[p1:p2]:
p2+=1
count=max(count,len(s[p1:p2]))
else:
while s[p2] in s[p1:p2]:
p1+=1
return count