LeetCode题目地址
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
工具:利用Math.max(Obj a,Obj b)
从a
和b
两个元素中挑选出的最大一个
方法1:利用HashMap
思路:
- 判断字符串为空的情景;
- 定义
HashMap<Character,Integer>
数据类型,Character
记录每个字符的,Integer
记录每个字符的最新的位置;j
来标记不重复字符串的起始位置; - 遍历字符串
s
,如果map
不包含,则存放该字符以及当前索引位置,定义res
变量,利用Math.max()
函数取(res, i-j+1)
中的最大值;如果map
包含该字符串,则利用j = Math.max(j,map.get(s.charAt(i))+1)
,让j
指向下一个不重复字符的起始位置。
注:每一次利用res = Math.max(res, i-j+1);
计算当前字符串的长度,并与当前存储的最大值res
比较,取最大的一个,从而保证res
动态更新;
j = Math.max(j,map.get(s.charAt(i))+1);
中j
的取值不能直接使用j =map.get(s.charAt(i))+1;
,因为这种写法没有把abba
的情景考虑在内
具体代码:
public class Solution3 {
public static int lengthOfLongestSubstring(String s) {
if (s == null ||s.length() ==0)
return 0;
HashMap<Character,Integer> map = new HashMap<>();
int res =0;
for (int i=0,j=0; i<s.length() ; i++){
if (map.containsKey(s.charAt(i))){
j = Math.max(j,map.get(s.charAt(i))+1);
}
map.put(s.charAt(i),i);
res = Math.max(res, i-j+1);
}
return res;
}
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstring("abcabccd"));;
}
}
方法2:利用HashSet
(推荐)
思路:
利用HashSet
的元素的不重复特性,HashSet
中能存放元素最长的时候,就是无重复字符的最长子串的时候
具体代码:
public class Solution3 {
public static int lengthOfLongestSubstring2(String s) {
if (s == null ||s.length() ==0)
return 0;
HashSet<Character> set = new HashSet<>();
int res =0;
for (int i=0,j=0; i<s.length() ; i++){
if (set.contains(s.charAt(i))){
set.remove(s.charAt(j++));
}else {
set.add(s.charAt(i));
res = Math.max(res, set.size());
}
}
return res;
}
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstring2("abcabccd"));;
}
}