3. 无重复字符的最长子串-滑动窗口

4 阅读1分钟
class Solution {
    public int lengthOfLongestSubstring(String s) {
        //不重复最长子串,想到滑动窗口和dp,因为可以分解为同类子问题
        //1.定义dp[i]以i结尾的最长字符串
        //2.状态转移方程:dp[i]=dp[i-1]
        HashMap<Character, Integer> map = new HashMap<>();
        int i = -1; int res = 0;
        for(int j = 0; j < s.length(); j++){
            if(map.containsKey(s.charAt(j))){
                i = Math.max(i, map.get(s.charAt(j)));
            }
            map.put(s.charAt(j), j);
            res = Math.max(res, j - i);
        }
        return res;
    }
}