字符串中最长不含重复字符的子字符串
package offer;
import java.util.HashMap;
import java.util.Map;
/**
* 字符串中最长不含重复字符的子字符串
*
* @author xiaowang
*
*/
public class offer48 {
public static void main(String[] args) {
String s = "abbabc";
int result = longestSubString(s);
System.out.println(result);
}
private static int longestSubString(String s) {
Map<Character, Integer> map = new HashMap<>();
int now = 0;
int maxLength = 0;
for (int i = 0; i < s.length(); i++) {
// 如果map中包括key
if (map.containsKey(s.charAt(i))) {
// 更新now
now = Math.max(now, map.get(s.charAt(i)) + 1);
}
// 如果重复的字符串在now之前 则更新长度
if (i - now + 1 > maxLength) {
maxLength = i - now + 1;
}
map.put(s.charAt(i), i);
}
return maxLength;
}
}