问题描述:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
思路:
- 动态指针(滑动窗口):设置首尾指针,初始指向首字符,同时设置最长子串长度max。尾指针后移,若所指新字符不为重复字符,继续后移;否则停止后移,但首指针后移,直至子串中没有重复指针。重复上述步骤直至遍历结束。
//cpp动态指针
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int max, len, head, tail;
len = max = head = tail = 0;
while(tail < size(s)){
for(int i = head; i < tail; ++i){
if(s[tail] == s[i]){
head = i + 1;
len = tail - head;
}
}
++tail;
++len;
if(len > max) max = len;
}
return max;
}
};
#(python)
class Solution:
#基于数组,可通过双指针优化
def lengthOfLongestSubstring(self, s: str) -> int:
lst = []
maxstr = 0
for c in s:
if c not in lst:
lst.append(c)
else:
lst = lst[lst.index(c)+1:]#直接将初始位置跳转到重复字符后
lst.append(c)
if len(lst) > maxstr:maxstr = len(lst)
return maxstr
#方法二:基于字典
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dic = {}
maxlength = 0
head = -1//指向最近重复字符
for i,c in enumerate(s):
if c in dic and head < dic[c]:
head = dic[c]
dic[c] = i
else:
dic[c] = i
maxlength = max(maxlength, i - head)
return maxlength