LeetCode每日一题:longest substring without repeating characters

问题描述

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

问题分析

一般查找是否重复最简便的方法就是hashMap,这道题只要求我们返回长度大小,我们可以采用滑动窗口的方式来进行。

代码实现

public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) return 0;
        HashMap hashMap = new HashMap<>();
        int leftBound = 0;
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int isSame = 0;
            if (hashMap.containsKey(c)) isSame = hashMap.get(c) + 1;
            leftBound = Math.max(leftBound, isSame);
            max = Math.max(max, i - leftBound + 1);
            hashMap.put(c, i);
        }
        return max;
    }

你可能感兴趣的:(LeetCode每日一题:longest substring without repeating characters)