CodeCollection2018
8/28/2019 - 9:04 AM

Longest Substring Without Repeating Characters--最长无重复字符子串


	public static int longestNoDupSubstring(String s) {
		if(s==null || s.length()==0) return 0;
		int res = 0;
		Map<Character,Integer> hash = new HashMap<>();//存储字符及其出现的位置
		int start =  0;
		for(int i = 0 ; i < s.length(); i++) {
			char cur = s.charAt(i);
			if(hash.isEmpty() || !hash.containsKey(cur)) {
				hash.put(cur, i);
				continue;
			}else {
				int pre_index_of_cur = hash.get(cur);
				res = res>hash.entrySet().size()?res:hash.entrySet().size();
				for(int j=start;j <= pre_index_of_cur; j++) {
					if(hash.containsKey(s.charAt(j)))
						hash.remove(s.charAt(j));
				}
				start = pre_index_of_cur+1;
				hash.put(cur, i);
			}
		}
		return res;
	}