【LeetCode】3. Longest Substring Without Repeating Characters - Java实现

      • 1. 题目描述:
      • 2. 思路分析:
      • 3. Java代码:

1. 题目描述:

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.

2. 思路分析:

整个过程遍历一次字符串,用一个Map来存储已经出现过的字符和其下标的映射关系,用一个值maxLen来记录无重复字符子串的最大长度,用left来记录当前无重复字符子串的最左边字符的下标。遍历整个字符串的过程中,当出现重复的字符时,计算当前最大长度,并与记录的最大长度maxLen比较来判断是否更新最大长度maxLen的值,并更新left的值与Map中重复字符对应的下标值。

3. Java代码:

源代码:见我GiHub主页

class Solution {
    public static int lengthOfLongestSubstring(String s) {
        // 用于记录字符到下标的映射,重复字符记录最大的下标
        Map itemToIndexMap = new HashMap<>();
        int maxLen = 0;
        // 用于记录当前无重复字符串的最左下标
        int left = 0;

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            // 注意此处的第二个判断条件,虽然出现了重复字符,但不在当前的子串范围内,故不影响
            if (!itemToIndexMap.containsKey(ch) || itemToIndexMap.get(ch) < left) {
                itemToIndexMap.put(ch, i);
                continue;
            }

            // 更新最大长度值
            maxLen = Math.max(maxLen, i - left);
            // 更新最左下标
            left = Math.max(left, itemToIndexMap.get(ch) + 1);
            // 更新重复字符的下标
            itemToIndexMap.put(ch, i);
        }

        maxLen = Math.max(maxLen, s.length()  - left);
        return maxLen;
    }
}

你可能感兴趣的:(【LeetCode】,【Java】,LeetCode题解,-,Java实现)