给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
思路:
1.给定一个map
class Solution {
public int lengthOfLongestSubstring(String s) {
int n=s.length();
int ans=0;
Map<Character, Integer> map = new HashMap<>();
for(int start=0, end=0;end<n;end++){
char key=s.charAt(end);
if(map.containsKey(key)){
start=Math.max(map.get(key),start);
}
ans=Math.max(ans,end-start+1);
map.put(s.charAt(end),end+1);
}
return ans;
}
}
原文:https://www.cnblogs.com/caiyideboke/p/11726246.html