题解 | #最长不含重复字符的子字符串#

最长不含重复字符的子字符串

https://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int lengthOfLongestSubstring (String s) {
        // write code here
        if(s.length()==0)
            return 0;
        int[] counts = new int[256];
        int left = 0;
        int countDup = 0; //记录是否出现重复字符
        int max = 0; //记录最大长度
        int right = 0;
        for(;right<s.length();right++){
            counts[s.charAt(right)]++;
            if(counts[s.charAt(right)]==2){
                countDup++;
                max = Math.max(max,right-left);
            }
            while(countDup>0){
                counts[s.charAt(left++)]--;
                if(counts[s.charAt(right)]==1){
                    countDup--;
                }
            }
        }
        return Math.max(max,right-left);

    }
}

全部评论

相关推荐

2024-12-23 06:50
门头沟学院 Java
给点吧求求了:3点发的帖子,害怕😰
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务