【LeetCode】Longest Substring Without Repeating Characters 解题报告

【题意】

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

【思路】

一開始我是用 HashMap 做的,然后就在考虑 字母做key还是下标做key,总之比較麻烦。

后来看到网上普遍用数组来实现 HashMap 的功能。感觉还是挺新的。

至于为什么数组的大小设为256,始终想不明确。我查了下ASCII码表,上面也仅仅有127个字符。A~Z是65~90,a~z是97~112。

以下的代码我认为是已经相当简洁了。參考出处:JavaC++。大家共同学习。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        if (s == null || len == 0) return 0;
        
        int[] table = new int[256];
        Arrays.fill(table, -1);
        
        int maxlen = 1;
        int begin = 0, end = 1;
        table[s.charAt(0)] = 0; //important!
        while (end < len) {
            char endch = s.charAt(end);
            if (table[endch] >= begin) {
                begin = table[endch] + 1;
            }
            table[endch] = end;
            maxlen = Math.max(maxlen, end-begin+1);
            end++;
        }
        
        return maxlen;
    }
}

上面代码有下面优点:它推断有没有反复是通过当前字母在table中的值是不是比子串的開始位置大,这样就不用每次出现反复字母后都须要把之前的字符在table中的值又一次设为-1。


转载于:https://www.cnblogs.com/zhchoutai/p/6920173.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值