welcome to my blog
LeetCode Top 100 Liked Questions 3. Longest Substring Without Repeating Characters(Java版; Medium)
题目描述
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
if(n<=1){
return n;
}
int left=0, right=0;
int max = 1;
Map<Character,Integer> map = new HashMap<>();
boolean flag = false;
while(right<n){
char ch = s.charAt(right);
if(map.containsKey(ch)){
// 注意:map.get(ch)+1可能比当前的left小!
left = Math.max(left, map.get(ch)+1);
}
map.put(ch, right);
max = Math.max(max, right - left + 1);
right++;
}
return max;
}
}
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
if(n<=1){
return n;
}
int left=0, right=0;
int max = 1;
Map<Character,Integer> map = new HashMap<>();
boolean flag = false;
while(right<n){
char ch = s.charAt(right);
map.put(ch, map.getOrDefault(ch, 0)+1);
if(map.get(ch)==2){
while(map.get(ch)==2){
char ch2 = s.charAt(left);
map.put(ch2, map.get(ch2)-1);
left++;
}
}
max = Math.max(max, right - left + 1);
right++;
}
return max;
}
}
第一次做, 更新左边界的while循环最重要, 在寻找和右边界元素相同的元素时, 需要把沿途碰到的出现过的元素的出现次数重新赋值为0; 这题有点类似剑指offer面试题42连续子数组的最大和, 不过这两道题更新左边界的思想是不同的
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s==null || s.length()==0)
return 0;
int left=0;
int[] arr= new int[128];
int max=0;
for(int right=0; right<s.length(); right++){
if(arr[s.charAt(right)]==0){
arr[s.charAt(right)]++;
max = Math.max(max, right - left + 1);
}
else{ //arr[s.charAt(right)]==1
//找到重复的元素
while(s.charAt(left)!=s.charAt(right)){
//寻找和右边界元素相同的元素时, 沿途碰到的其他出现过的元素需要把出现次数减为0
if(arr[s.charAt(left)]==1)
arr[s.charAt(left)]--;
left++;
}
//更新左边界
left++;
}
}
return max;
}
}
题解中的答案, 和我的想法一致, 但是做法简介; 使用哈希表记录出现过的元素及对应的索引, 之后之后再遍历到该元素, 需要更新左边界left吗? 不一定, 如果哈希表中该元素对应的索引小于left就不用更新left, 如果哈希表中该元素对应的索引大于等于left, 就得更新left, 代码中用left=Math.max()实现这个想法, 比我的while循环快
- “abctbefa” 第二次碰到a的时候, 由于此时左边界left指向c, 哈希表中a的索引小于left, 所以不用更新left. 注意这之后得接着更新a在哈希表中的索引, 体现了execute → update 处理流程
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length()==0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max = 0;
int left = 0;
for(int i = 0; i < s.length(); i ++){
if(map.containsKey(s.charAt(i))){
left = Math.max(left,map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i),i);
max = Math.max(max,i-left+1);
}
return max;
}
}