3. Longest Substring Without Repeating Characters最长不重复子串

Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, 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.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0)
            return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max = 0;
        //i遍历字符串,j记录所求串的first字符
        for (int i = 0, j = 0; i < s.length(); ++i) {
            if (map.containsKey(s.charAt(i))) {
// 为保证j有效前提,取j和当前字符在map中的重复位置的最右值: 继续寻找
                j = Math.max(j, map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i), i);
            max = Math.max(max, i - j + 1);//每次循环后,更新max值
        }
        return max;
    }
}

不理解 j = Math.max(j, map.get(s.charAt(i)) + 1); 时,可以参考下面:

The variable “j” is used to indicate the index of first character of this substring. If the repeated character’s index is less than j itself, which means the repeated character in the hash map is no longer available this time

例如:“abcba”
j:不重复子串的first
i:不重复子串的end;

当i=3,时,判断map中已有b,则j=原有值的索引(1)+1=2;(所求串中b不重复,最多从索引2开始)
当i=4,时,判断map中已有a,此时若直接将所求不重复子串的初始位置j=原有值的索引(0)+1=1,则会出现,之前所求的重复b矛盾失效;
因此,在赋值所求不重复子串的初始位置j时,需要考虑到所有字符的不重复的最大值;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值