[leetcode]Longest Substring Without Repeating Characters

本文探讨了LeetCode上的一道经典问题:寻找字符串中最长的无重复字符子串。通过递归与动态规划两种方法进行实现并对比,重点介绍了如何使用动态规划解决该问题。

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

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.

 求最长不重复子串,很经典的DP问题(DP好渣。。。。)

第一反应时用递归:但是时间复杂度还是达到了O(n^2),leetcode的数据总是强到本地无法测试。。。。,以下是递归实现的代码:

public int lengthOfLongestSubstring(String s) {
        if(s == null || s.isEmpty()){
        	return 0;
        }
        int maxLength = 0;
        int tem = 0;
        int from = 0;
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i = 0 ; i < s.length(); i++){
        	if(!map.containsKey(s.charAt(i))){
        		map.put(s.charAt(i),i);
        		maxLength++;
        	}else{
        		from = map.get(s.charAt(i)); //重复字母上次出现的位置
        		tem = lengthOfLongestSubstring(s.substring(from + 1));
        		break;
        	}
        }
	return maxLength > tem ? maxLength : tem ;
	}

  超时。。。。

下面来看DP实现,由于懒得再写Hash,偷懒用了hashMap,道理是一样的。

public int lengthOfLongestSubstring(String s) {
		int length = s.length();
		Map<Character,Integer> hash = new HashMap<Character,Integer>();
		int currentLength  = 0;
		int maxLength = 0;
		int from = 0;
		for(int i = 0; i < length; i++){
			if(!hash.containsKey(s.charAt(i))){
				currentLength++;
				hash.put(s.charAt(i), i);
			}else{
				if(from <= hash.get(s.charAt(i))){
					from = hash.get(s.charAt(i)) + 1;
					currentLength = i - hash.get(s.charAt(i));
					hash.put(s.charAt(i), i);
				}else{
					currentLength++;
					hash.put(s.charAt(i), i);
				}
			}
			if(currentLength > maxLength){
				maxLength = currentLength;
			}
		}
		return maxLength;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值