package com.sample.suncht.algo;
import java.util.*;
/**
* 3. 无重复字符的最长子串
* 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
* 示例 3:
* <p>
* 输入: "pwwkew"
* 输出: 3
* 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
* 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
*
* 时间复杂度:O(n), 空间复杂度:O(n)
* @author sunchangtan
* @date 2019/3/1 20:26
*/
public class LengthOfLongestSubstring {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0) {
return 0;
}
char[] chars = s.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
int head = 0;
int tail = 0;
int maxLen = 0;
for (int i = 0; i < chars.length; i++) {
if(!map.containsKey(chars[i])) {
head = i;
map.put(chars[i], i);
if(i == chars.length - 1) {
maxLen = Math.max(head - tail + 1, maxLen);
tail = i;
}
} else {
maxLen = Math.max(head - tail + 1, maxLen);
int oldIndex = map.get(chars[i]);
for (int j = tail; j < oldIndex + 1; j++) {
map.remove(chars[j]);
}
tail = oldIndex + 1;
head = i;
map.put(chars[i], i);
}
}
return maxLen;
}
public static void main(String[] args) {
List<AlgoHelper.InputParams<String, Integer>> datas = new ArrayList<>();
datas.add(new AlgoHelper.InputParams<>("a", 1));
datas.add(new AlgoHelper.InputParams<>("ab", 2));
datas.add(new AlgoHelper.InputParams<>("", 0));
datas.add(new AlgoHelper.InputParams<>(" ", 1));
datas.add(new AlgoHelper.InputParams<>("cacd", 3));
datas.add(new AlgoHelper.InputParams<>("pwwkew", 3));
datas.add(new AlgoHelper.InputParams<>("122493", 4));
datas.add(new AlgoHelper.InputParams<>("abcabcbb", 3));
datas.add(new AlgoHelper.InputParams<>(null, 0));
datas.add(new AlgoHelper.InputParams<>("cdd", 2));
datas.add(new AlgoHelper.InputParams<>("cdqdc", 3));
AlgoHelper.assertResult(datas, new LengthOfLongestSubstring()::lengthOfLongestSubstring);
}
}