暴力
class Solution { public int lengthOfLongestSubstring(String s) { int the_max = 0; HashSet hs = new HashSet(); for (int i = 0; i < s.length(); i++) { hs.clear(); int y = i; while ( y < s.length() ) { if ( hs.contains(s.charAt(y))) break; else { hs.add(s.charAt(y)); y++; } } the_max = Math.max(hs.size(), the_max); hs.clear(); } return the_max; } }
第二种解法 双指针做法
class Solution { public int lengthOfLongestSubstring(String s) { int the_max = 0; HashSet hs = new HashSet(); for(int i = 0,j =0 ; i < s.length() ; i++) { while(hs.contains(s.charAt(i))) { hs.remove(s.charAt(j)); j++; } hs.add(s.charAt(i)); the_max = Math.max(i-j+1,the_max); } hs.clear(); return the_max; } }