采用滑动窗口法解决问题,相比较暴力解法的优化点:
package demo1;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class LengthOfLongestSubstringPlus {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int max = 0;
Map<Character, Integer> map = new HashMap<>();
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
max = Math.max(max, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return max;
}
public static void main(String[] args) {
LengthOfLongestSubstringPlus l = new LengthOfLongestSubstringPlus();
Scanner sc = new Scanner(System.in);
int max = 0;
String str;
System.out.println("输入str");
str = sc.nextLine();
max = l.lengthOfLongestSubstring(str);
System.out.println("max = " + max);
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容