题目:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
思路:
1、遍历字符串,用一个字典dt来存储每个元素的索引位置,用left变量存储子串的左端点,用right变量用来存储子串的右端点
Python代码:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
dt = {}
left = 0
ans = 0
for right,item in enumerate(s):
if item in dt:
left = max(dt[item], left)
dt[item] = right+1
ans = max(ans, right-left+1)
return ans
C++代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<int, int> dt;
int start=0, ans=0;
for (int index=0; index<s.size(); index++){
char item = s[index];
if(dt.find(item)!=dt.end()){
start = max(start, dt[item]);
}
dt[item] = index+1;
ans = max(ans, index-start+1);
}
return ans;
}
};
思路2(改进):
1、思路和上面的方法类似,不过起始节点的值设置为-1
Python代码:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
# abcabcbb
dt = {}
start, ans = -1,0
for index, item in enumerate(s):
if item in dt:
start = max(start, dt[item])
dt[item] = index
ans = max(ans, index-start)
return ans
C++代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<int, int> dt;
int start=-1, ans=0;
for (int index=0; index<s.size(); index++){
char item = s[index];
if(dt.find(item)!=dt.end()){
start = max(start, dt[item]);
}
dt[item] = index;
ans = max(ans, index-start);
}
return ans;
}
};
网友评论