【LeetCode】 3. Longest Substring Without Repeating Characters 无重复字符的最长子串 (Medium)(JAVA)

【LeetCode】 3. Longest Substring Without Repeating Characters 无重复字符的最长子串 (Medium)(JAVA)

题目地址: https://leetcode.com/problems/longest-substring-without-repeating-characters/

题目描述:

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

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

题目大意

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

解题方法

用一个变量记录开始的位置,用一个数组来记录是否有过当前字母;
遇到有过当前字母,从开始的位置开始不断往后遍历,直到找到相同字母为止,同时减去遍历过的字母。
Accepted

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int max = 0;
        int[] count = new int[128];
        int start = 0;
        for (int i = 0; i < s.length(); i++) {
            if (count[s.charAt(i)] == 0) {
                count[s.charAt(i)]++;
            } else {
                while (s.charAt(i) != s.charAt(start)) {
                    count[s.charAt(start)]--;
                    start++;
                }
                start++;
            }
            if ((i - start + 1) > max) max = i - start + 1;
        }
        return max;
    }
}

执行用时 : 4 ms, 在所有 Java 提交中击败了91.09%的用户
内存消耗 : 38.9 MB, 在所有 Java 提交中击败了12.34%的用户

发布了29 篇原创文章 · 获赞 3 · 访问量 1117

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104504401