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

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

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
        HashMap<Character, Integer> charSet = new HashMap<>();
        int result = 0;
        for(int left = 0, right = 0; right < s.length(); right ++){
            if(charSet.containsKey(s.charAt(right))) charSet.put(s.charAt(right), charSet.get(s.charAt(right)) + 1);
            else charSet.put(s.charAt(right), 1);
            while(charSet.get(s.charAt(right)) > 1) charSet.put(s.charAt(left), charSet.get(s.charAt(left ++)) - 1);
            result = Math.max(result, right - left + 1);
        }
        return result;
    }
}

全部评论

相关推荐

喜欢吃卤蛋的肖恩在参加牛客活动:你们结束聊天,是不是还要来个四次挥手😂
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务