無重複字符的最長子串spa
解題思想:滑動窗口code
方法1blog
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; } }
方法2get
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; } }