import java.util.*;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int lengthOfLongestSubstring (String s) {
        // write code here
        if(s.length() <= 1){return s.length();}
        int[] len = new int[s.length()];  //记录当前字符串长度
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();  //记录字符和索引
        int maxlength = 1;  //字符串最大长度
        //边界条件
        len[0] = 1; 
        map.put(s.charAt(0),0);
        
        for(int i = 1; i < s.length(); i++){
            if(!map.containsKey(s.charAt(i))){
                len[i] = len[i - 1] + 1;
            }
            else {
                int theBeforeIndex = map.get(s.charAt(i));
                int tmpCount = i - theBeforeIndex;
                len[i] = Math.min(tmpCount, len[i - 1] + 1);
            }
            map.put(s.charAt(i), i);
            maxlength = Math.max(maxlength,len[i]);
        }
        
        return maxlength;
    }
}