3. Longest Substring Without Repeating Characters

本文介绍了一种求解字符串中最长无重复字符子串长度的高效算法。通过双指针与哈希映射结合的方法,实现了动态更新最长子串长度的功能。适用于面试和技术交流。

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

一,题目

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.

二,思路

使用两个指针一个指向子串的头,一个指向子串的尾, 然后一直向后移动尾指针,将每次一动的元素保存到hashmap key是字符值,value是其在字符串中对应的索引。
每次移动尾指针,判断其是否在hashmap中,如果不在,继续后移动;否则,说明找到了一个不重复的子串,比较长度,然后头指针向前移动一个,然后继续一直移动尾指针。


三,代码如下

public int lengthOfLongestSubstring(String s) {
        <span style="white-space:pre">	</span>int maxLen = 0;
		if (s == null) {
		<span style="white-space:pre">	</span>return maxLen;
		}
		Map<Character, Integer> map = new HashMap<Character, Integer>();
		int start = 0;
		for (int i = 0, len = s.length(); i < len; i++) {
			char c = s.charAt(i);
			Integer index = map.get(c);
			if (index != null) {
				if(index < start){
					map.put(c,i);
					continue;
				}
				maxLen = maxLen > i - start ? maxLen : i - start;
				start = index+1;
			}
			map.put(c, i);
		}
		maxLen = maxLen > (s.length() - start) ? maxLen : s.length() - start;
		return maxLen; 
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值