LeetCode-3-无重复字符的最长字串--力扣官网第3题

13 阅读1分钟

#无重复字符的最长字串 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。 示例 1:

输入: s = "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 示例 2:

输入: s = "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 示例 3:

输入: s = "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

思路: 1.start不动,end向后移动 2.当end遇到重复字符,start应该放在上一个重复字符的位置的后一位,同时记录最长的长度(end-start+1) 3.怎样判断是否遇到重复字符,且怎么知道上一个重复字符的位置?--用HashMap的key来判断是否重复,用value来记录该字符的下一个不重复的位置。

public class Test04 {
    public static void main(String[] args) {
        String s = "pwwkew";
        Test04 test = new Test04();
        int i = test.lengthOfLongestSubstring(s);
        System.out.println("不含有重复字符的最长字串的长度为:" +"\t"+ i);
    }

    public int lengthOfLongestSubstring(String s) {
        int length = s.length();
        int max = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int start = 0, end = 0; end < length; end++) {
            char element = s.charAt(end);
            if (map.containsKey(element)) {
                start = Math.max(map.get(element) + 1, start);
            }
            max = Math.max(max, end - start + 1);
            map.put(element, end);
        }
        return max;
    }
}

结果 在这里插入图片描述