您的位置:首页 > 其它

leetcode 3 无重复字符的最长子串

2019-05-23 16:20 465 查看

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

示例 1:

输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:

输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:

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

解题思路: 滑动窗口

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int freq[256] = {0};
int l = 0;
int r = -1;
int len = 0;
while(l < s.size()){
if( freq[s[r+1]] == 0 && r+1<s.size())
freq[s[++r]]++;
else
freq[s[l++]]--;

len = max(len,r-l+1);

}
return len;

}
};
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
freq = [0] * 256
l,r = 0,-1
res = 0

while( l < len(s) ):
if( r + 1 < len(s) and freq[ord(s[r + 1])] == 0):
r += 1
freq[ord(s[r])] += 1
else:
freq[ord(s[l])] -= 1
l += 1

res = max( res , r-l+1 )
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: