题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
思路1:
时间效率不高,只打败了19%
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() < 1)
return 0;
char[] arr = s.toCharArray();
int max = Integer.MIN_VALUE;
for(int i = 0;i < arr.length;i++){
int count = 1;
char c = arr[i];
HashSet<Character> hs = new HashSet<>();
hs.add(c);
for(int j = i+1;j < arr.length;j++){
if(hs.contains(arr[j])){
break;
}
count++;
hs.add(arr[j]);
}
max = count > max? count:max;
}
return max;
}
}
2.学习别人的做法,使用滑动窗口的方法
时间复杂度O(n)
class Solution {
public int lengthOfLongestSubstring(String s) {
//使用滑动窗口来解决问题
if(s == null || s.length() < 1)
return 0;
int left = 0;//来指示左边界
int max = 0;
//HashMap里存储的是 字符-索引 的映射
HashMap<Character,Integer> hm = new HashMap<>();
for(int i = 0; i < s.length();i++){
char c = s.charAt(i);
if(hm.containsKey(c)){
//左边界进行重选
left = Math.max(hm.get(c)+1,left);
//System.out.println("left:"+left);
}
hm.put(c,i);
max = Math.max(max,i-left+1);
//System.out.println("max:"+max);
}
return max;
}
}