问题描述:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
解题思路:
思路与第一题有点类似,同样是用HashMap来存储数组值和下标,其中数组值为HashMap中的key值,数组下标为HashMap中的value值。不同的是,这次需要一个类似于C++中的指针来指明字串的起点。也就是说,每次添加一个key值时,是从指针往后的范围比较是否重复的,如果重复的话则将指针移动到该值下一个下标处,否则往HashMap中继续添加键值并往后比较。
代码如下:
public class Solution { public int lengthOfLongestSubstring(String s) { Map<Character, Integer> map = new HashMap<Character, Integer>(); int length = 1; int sum = 0; int pointer = 0; if (s == null || s.length() == 0) return 0; for (int i = 0; i < s.length(); i++) { if (map.containsKey(s.charAt(i)) && map.get(s.charAt(i)) >= pointer) { Integer tmp = map.get(s.charAt(i)); sum = i - pointer; length = Math.max(sum, length); pointer = tmp + 1; map.put(s.charAt(i), i); } else { map.put(s.charAt(i), i); } } length = Math.max(s.length() - pointer, length); return length; } }