一、题目说明

二、求解方法
2.1 暴力法
1、思路
2、代码
package question4.solution1;
import java.util.HashSet;
/**
* @description: 暴力法
* @author: hyr
* @time: 2020/3/26 15:40
*/
public class Solution {
public static void main(String[] args) {
String s = "abcccccaaaa";
System.out.println(lengthOfLongestSubstring(s));
}
public static int lengthOfLongestSubstring(String s){
int n = s.length();
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1 ; j <= n ; j++) {
if (allUnique(s, i, j)){
// 这里是比较这一次与上一次的子串长度
ans = Math.max(ans, j - i);
}
}
}
return ans;
}
public static boolean allUnique(String s, int start, int end){
HashSet<Character> set = new HashSet<>();
for (int i = start; i < end; i++) {
char ch = s.charAt(i);
if (set.contains(ch)){
return false;
}
set.add(ch);
}
return true;
}
}
2.2 滑动窗口法
1、思路
2、代码
package question4.solution2;
import java.util.HashSet;
import java.util.Set;
/**
* @description: 滑动窗口法
* @author: hyr
* @time: 2020/3/26 15:40
*/
public class Solution {
public static void main(String[] args) {
String s = "abccccaabcdeaa";
System.out.println(lengthOfLongestSubstring(s));
}
public static int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
} else {
set.remove(s.charAt(i++));
}
}
return ans;
}
}
版权声明:本文为a1786742005原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。