Given a string, find the length of the longest substring without repeating characters.
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.
测试用例构建
[],
[a,a,a,a]
[a]
[abca]
import java.util.*;
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length()==0)
return 0;
int sum = 1;
HashMap<Character,Integer> map = new HashMap<>();
int i = 0;
for(int j = 0 ; j < s.length();j++){
char ch = s.charAt(j);
if(map.containsKey(ch)){
int index = map.get(ch);
if(sum < j-i)
sum = j-i;
for(;i<=index;i++)
map.remove(s.charAt(i));
i = index+1;
}
map.put(ch,j);
}
if(sum >= s.length()-i)
return sum;
else
return s.length()-i;
}
}
Given a string, find the length of the longest substring without repeating characters.
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.
测试用例构建
[],
[a,a,a,a]
[a]
[abca]
import java.util.*;
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length()==0)
return 0;
int sum = 1;
HashMap<Character,Integer> map = new HashMap<>();
int i = 0;
for(int j = 0 ; j < s.length();j++){
char ch = s.charAt(j);
if(map.containsKey(ch)){
int index = map.get(ch);
if(sum < j-i)
sum = j-i;
for(;i<=index;i++)
map.remove(s.charAt(i));
i = index+1;
}
map.put(ch,j);
}
if(sum >= s.length()-i)
return sum;
else
return s.length()-i;
}
}
一种更好的方法就是不用每次都清理hashmap,可以保持hashmap只不过判断时候 i = Math.max(i,map.get(s.charAt(j))+1);
Longest Substring with At Most Two Distinct Characters
Medium
Longest Substring with At Most K Distinct Characters
Hard
Subarrays with K Different Integers
Hard
leetcode 3. Longest Substring Without Repeating Characters
原文:https://www.cnblogs.com/clnsx/p/12272610.html