//方法一:使用HashMap记录字符的位置,实现滑动窗口
public class LengthOfLongestSubstring {
public int lengthOfLonggestSubstring(String s) {
if(s == null) { throw new IllegalArgumentException(); }else { Map<Character, Integer> map = new HashMap<>(); char ch = ‘ ‘; int maxLen = 0; int subIndex =0; for(int i=0; i < s.length(); i++) { ch = s.charAt(i); if(!map.containsKey(ch)) { map.put(ch, i); maxLen = Math.max(maxLen, i - subIndex + 1); }else { //若出现重复字符,判断重复字符索引是否大于当前开始索引,若是,则将左侧开始索引更改为重复字符后一位 subIndex = Math.max(map.get(ch) + 1, subIndex); //更改重复字符索引为新的位置 map.put(ch, i); //如果重复字符索引小于当前开始索引,字符串长度会加1,否则得到的结果比实际值小1 maxLen = Math.max(maxLen, i - subIndex + 1); } } return maxLen; } } }
//方法二:
public int lengthOfLonggestSubstring(String s) { if(s == null) { throw new IllegalArgumentException(); }else if(s.equals("")) { return 0; }else { Set<Character> set = new HashSet<>(); int i=0; int j=0; int len = s.length(); int maxLen = 0; while(i < len && j < len) { if(!set.contains(s.charAt(j))) { set.add(s.charAt(j)); j++; maxLen = Math.max(maxLen, j-i); }else { //可以确定出现重复字符后的重新开始的位置,比如abcbad,出现重复的b后,会删除最开始的ab, //从c开始 set.remove(s.charAt(i)); i++; } } return maxLen; } }
原文:https://www.cnblogs.com/xiyangchen/p/10804681.html