Problem Statement#
Given a string, find the length of the longest substring, which has all distinct characters.
Example 1:
Input: String="aabccbb"Output: 3Explanation: The longest substring with distinct characters is "abc".
Example 2:
Input: String="abbbb"Output: 2Explanation: The longest substring with distinct characters is "ab".
Example 3:
Input: String="abccde"Output: 3Explanation: Longest substrings with distinct characters are "abc" & "cde".
不重复的连续子字符串
public static int findLength(String str) {
HashMap<Character, Integer> map = new HashMap<>();
int sum = 0;
char[] chars = str.toCharArray();
int start = 0;
int result = Integer.MIN_VALUE;
for(int i = 0; i < chars.length; i++){
char c = chars[i];
map.put(chars[i],map.getOrDefault(c,0) + 1);
while ( map.getOrDefault(c, 0) > 1){
map.put(chars[start],map.getOrDefault(chars[start], 0) -1);
start++;
}
result = Math.max(result, i - start + 1);
}
return result != Integer.MIN_VALUE ? result : -1;
}
近期评论