一.问题描述
Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
二.编写代码
1.输入:字符串
2.输出:最长不重复子串的长度
代码如下:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
len_s=len(s)
#处理特殊情况:s为空字符串
if len_s==0:
return 0
max_len=1
#两个指针初始化
i=0
j=1
while (j<len_s):
while (s[i:j].find(s[j])<0):
#j指针前面没有与j指向的字符相同的
j=j+1
if j>=len_s:
break
if max_len<j-i:
max_len=j-i
if j<len_s:
i=s[i:j].find(s[j])+1+i
return max_len
算法效率不错,如下图:
三.算法思想
通过使用两个指针i,j,初始化i=0,j=1。通过使j向右移动直至当前j所指向的字符与子串s[i:j]中某个字符重复,此时j-i即为一个不重复的子串,之后i重新赋值为当前子串相同字符的后一位,j再右移寻找新的不重复子串。该循环的过程中不断比较得出最长的不重复子串的长度。