classSolution{ publicintlengthOfLongestSubstring(String s){ Set<Character> set = new HashSet<>(); int n = s.length(); int right = -1; int max = 0; for (int i = 0; i < n; i++) { if(i!=0){ set.remove(s.charAt(i-1)); } while (right+1<n && !set.contains(s.charAt(right+1))) { set.add(s.charAt(right+1)); ++right; } max = Math.max(max, right - i+1); } return max; } }
比较奇怪的是只是改变了边界为左闭右开性能居然下降了,于是又试了一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution{ publicintlengthOfLongestSubstring(String s){ Set<Character> set = new HashSet<>(); int n = s.length(); int right = 0; int max = 0; for (int i = 0; i < n; i++) { if(i!=0){ set.remove(s.charAt(i-1)); } while (right<n && !set.contains(s.charAt(right))) { set.add(s.charAt(right)); ++right; } max = Math.max(max, right - i); } return max; } }