无重复字符的最长子串
解题思想:滑动窗口
方法1
class Solution { public int lengthOfLongestSubstring(String s) { int len = s.length(); if(len == 0){ return 0; } int begin = 0; int max = 1; String sub = null; int index = 0; for(int i=1;i<len;i++){ sub = s.substring(begin,i); index = sub.indexOf(s.charAt(i)); if(index!=-1){ if(max<i-begin){ max = i-begin; } begin += index+1; } } if(max<len-begin){ max = len - begin; } return max; } }
方法2
class Solution { public int lengthOfLongestSubstring(String s) { int len = s.length(); if(len == 0){ return 0; } int begin = 0; int max = 1; Integer index = 0; char c = 0; Map<Character,Integer> map = new HashMap<>(); map.put(s.charAt(0),0); for(int i=1;i<len;i++){ c = s.charAt(i); index = map.get(c); if(index!=null&&index>=begin){ if(max<i-begin){ max = i-begin; } begin = index+1; } map.put(c,i); } if(max<len-begin){ max = len - begin; } return max; } }