问题描述
输入一个字符串,输出其最长子串。“abbcd”中“abcd”不是子串
分析
从头到尾按字符扫描字符串,如果前面已经存在该字符假设位置为j,当前位置为i,则该子串的长度为(i-j),求他们最大值。(j 初始化为-1)
代码
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0){
return 0;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max = 0;
int i = 0, j = -1;
for (i = 0; i < s.length(); ++i) {
if (map.containsKey(s.charAt(i))) {
j = Math.max(j, map.get(s.charAt(i)));
}
map.put(s.charAt(i), i);
max = Math.max(max, i - j);
}
return max;
}