3.Longest Substring Without Repeating Characters

题目

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.

给出一个字符串,求出这个字符串不重复的子字符串的最长长度。

思路

利用 Map < Character, Integer > 来存储每一个字符以及出现的位置,用 i 来记录上一次出现重复字符的位置,用 j 记录从头到尾每个字符的下标,用 longest 记录最长无重复字符串的长度

    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> map = new HashMap<>();
        int longest = 0;
        for (int i = 0, j = 0; j < s.length(); j ++) {
            // 如果出现重复字符串,则获取重复字符串上一次出现的位置和现在的 i 的大小对比,将最大值赋值给 i
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            // 计算得到最长的不重复字符串长度
            longest = Math.max(longest, j - i + 1);
            // 将字符串以及位置放到Map中
            map.put(s.charAt(j), j + 1);
        }
        return longest;
    }

你可能感兴趣的:(LeetCode,LeetCode)