3. 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 subsequenceand not a substring.

一道非常经典的题目 vote达到1322

首先想到的是下面这个解法

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while (i < n && j < n) {
            // try to extend the range [i, j]
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans, j - i);
            }
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}

[i,j]标识不重复的substring 用set来保证 当遇到重复的 计算一下当前长度 然后从上一个重复的后面开始 循环
比如输入是”abcdecde
set里是abcde 当遇到第二个c 计算一下当前长度=3 然后i+1 也就是从第一个b开始

实际上我们不需要这样 每次i+1 对于上面这个例子 第二次计算 i直接从前一个重复字符位置后面 即d开始就可以了
因为c之前的位置都会包含c 导致重复
下面是优化后的解法 
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                //1.
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}

1.为什么是i = Math.max(map.get(s.charAt(j)), i);
而不是i = map.get(s.charAt(j));
testcase:abba
第二个a出现时 之后非重复子串的起始位置应该是第二个b 也就是i 而不是第一个a后面
所以要取i和前一个重复字符位置的最大值 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值