Leetcode: Longest Substring Without Repeating Characters

    xiaoxiao2024-11-04  76

    URL : https://leetcode.com/problems/longest-substring-without-repeating-characters/ 思路: 思路就是滑动窗口,当前字符在之前没有出现过,则窗口左端和右端都有效,如果出现重复,则移动窗口的左端直到当前位置的字符在字符串[left, current-1]中没有出现过,在变化的过程中记录最大的长度。下面给出代码。 代码:

    public int lengthOfLongestSubstring(String s) { int[] map = new int[256]; int curLen = 0; int max = 0; for (int i =0 ;i< s.length();i++) { int index = map[s.charAt(i) -0 ]; if (index == 0 || index > curLen ) { curLen++; max = Math.max(max,curLen); } else { max = Math.max(max,curLen); curLen = i - index + 1; } map[s.charAt(i) - 0] = i+1; } return max; }
    最新回复(0)