题目

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:

Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:

Input: “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

思路——Hash大法好

双指针移动。
Hash表查询字符是否出现。
时间复杂度 O ( L ) O(L) O(L),空间复杂度 O ( L ) O(L) O(L)

结果

Runtime: 27 ms, faster than 70.11% of Java online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 37.5 MB, less than 100.00% of Java online submissions for Longest Substring Without Repeating Characters.

源码

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> set = new HashSet<Character>();
        int ans = 0;
        int l, r = 0;
        Character c;
        int len = s.length();
        for (l = 0; l < len; ++l) {
            while (r < len) {
                c = s.charAt(r);
                if (set.contains(c)) {
                    ans = Math.max(ans,r-l);
                    break;
                } else {
                    set.add(c);
                    ++r;
                }
            }
            if (r == len) {
                ans = Math.max(ans, r - l);
                break;
            }
            set.remove(s.charAt(l));
        }
        return ans;
    }
}