一 挑战字符串
1 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
analyse:
hash表记录字符最近出现的索引,遍历到i位置时,求的是以当前位置i的字符为结尾的最长无重复子串。
code:
class Solution { public int lengthOfLongestSubstring(String s) { if (s == null || s.length() == 0) { return 0; } Map<Character, Integer> map = new HashMap<Character, Integer>(); int start = -1; int res = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (!map.containsKey(c)) { map.put(c, -1); } start = Math.max(start, map.get(c)); map.put(c, i); res = Math.max(res, i - start); } return res; } }