LeetCode - Longest Substring Without Repeating Characters

本文探讨了如何求解字符串中最长无重复字符子串的问题,并提供了三种不同的Java实现方案。通过逐步优化算法,最终采用了一个简洁高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/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.

这道题一开始我就想用Hashtable做,就是如果遇到重复字符,那么回到上一个该重复字符出现的下一个位置重新开始,

    public int lengthOfLongestSubstring(String s) {
        if(s==null || s.length()==0) return 0;
        int start = 0;
        int max = 1;
        while(start<(s.length()-1)){
            int end = start+1;
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            map.put(s.charAt(start), start);
            while(end < s.length()){
                if(map.containsKey(s.charAt(end))){
                    int localmax = end-start;
                    start = map.get(s.charAt(end))+1;
                    max = Math.max(max, localmax);
                    break;
                }
                else map.put(s.charAt(end), end);
                end++;
            }
            if(end == s.length()) break;
        }
        return max;
    }


结果超时了,后来发现其实不需要再检查两个重复字符之间的字符串了,因为它们已经被检查过了,肯定是不重复的。

public int lengthOfLongestSubstring(String s) {
        if(s==null || s.length()==0) return 0;
        int start = 0;
        int end = 0;
        int max = 1;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        while(end < s.length()){
            if(map.containsKey(s.charAt(end)) && map.get(s.charAt(end))>=start){
                max = Math.max(max, end-start);
                start = map.get(s.charAt(end))+1;
            }
            map.put(s.charAt(end), end);
            end++;
        }
        max = Math.max(max, end-start);
        return max;
    }


这样的话,判断一个字符是不是在start后面出现过,其实看它在hashtable中存储的出现点是在start前还是start后就行了。

所以后来发现原来直接用一个256的int数组就可以充当hashtable了。

public int lengthOfLongestSubstring(String s) {
        if(s==null || s.length()==0) return 0;
        int start = 0;
        int end = 0;
        int max = 1;
        int[] index = new int[256];
        Arrays.fill(index, -1);
        
        while(end<s.length()){
            if(index[s.charAt(end)]>=start){
                max = Math.max(max, end-start);
                start = index[s.charAt(end)] + 1;
            }
            
            index[s.charAt(end)] = end;
            end++;
        }
        max = Math.max(max, end-start);
        return max;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值