3.无重复字符的最长子串
1 //方法一:使用HashMap记录字符的位置,实现滑动窗口 2 public int lengthOfLonggestSubstring(String s) { 3 if(s == null) { 4 throw new IllegalArgumentException(); 5 }else { 6 Map<Character, Integer> map = new HashMap<>(); 7 char ch = ' '; 8 int maxLen = 0; 9 int subIndex =0; 10 for(int i=0; i < s.length(); i++) { 11 ch = s.charAt(i); 12 if(!map.containsKey(ch)) { 13 map.put(ch, i); 14 maxLen = Math.max(maxLen, i - subIndex + 1); 15 }else { 16 //若出现重复字符,判断重复字符索引是否大于当前开始索引,若是,则将左侧开始索引更改为重复字符后一位 17 subIndex = Math.max(map.get(ch) + 1, subIndex); 18 //更改重复字符索引为新的位置 19 map.put(ch, i); 20 //如果重复字符索引小于当前开始索引,字符串长度会加1,否则得到的结果比实际值小1 21 maxLen = Math.max(maxLen, i - subIndex + 1); 22 } 23 } 24 return maxLen; 25 }
26 }
1 // 该方法利用HashSet,使用滑动窗口的模式 2 public int lengthOfLonggestSubstring(String s) { 3 if(s == null) { 4 throw new IllegalArgumentException(); 5 }else if(s.equals("")) { 6 return 0; 7 }else { 8 Set<Character> set = new HashSet<>(); 9 int i=0; 10 int j=0; 11 int len = s.length(); 12 int maxLen = 0; 13 while(i < len && j < len) { 14 if(!set.contains(s.charAt(j))) { 15 set.add(s.charAt(j)); 16 j++; 17 maxLen = Math.max(maxLen, j-i); 18 }else { 19 //可以确定出现重复字符后的重新开始的位置,比如abcbad,出现重复的b后,会删除最开始的ab, 20 //从c开始 21 set.remove(s.charAt(i)); 22 i++; 23 } 24 } 25 return maxLen; 26 } 27 }
无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧