LeetCode【3. 无重复字符的最长子串】

工欲善其事必先利其器

题目:给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

public int lengthOfLongestSubstring(String s) {
    int n = s.length();
    int[] charIndex = new int[128]; // 用于存储字符的索引,ASCII字符集共有128个字符
    int maxLength = 0;
    int left = 0; // 左边界位置

    for (int right = 0; right < n; right++) {
        char currentChar = s.charAt(right);
        // 如果字符已经在窗口内出现过,将左边界移到上一次出现的位置之后
        if (charIndex[currentChar] > left) {
            left = charIndex[currentChar];
        }
        // 计算当前窗口的长度
        int windowSize = right - left + 1;
        // 更新字符索引
        charIndex[currentChar] = right + 1;
        // 更新最大长度
        maxLength = Math.max(maxLength, windowSize);
    }

    return maxLength;
}

猜你喜欢

转载自blog.csdn.net/s_sos0/article/details/132913126