[C++]LeetCode 3: Longest Substring Without Repeating Characters(最长不重复子串)

本文通过使用哈希表解决字符串中寻找无重复字符最长子串的问题,详细解析了解题思路并提供C++实现代码。

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

Problem:

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解决此问题(代码使用map)。其中键为字符,值为字符位置下标。设置起始位置位begin,每次查看字符c是否存在于map中,且下标是否大于begin(在当前子串范围内)。若是则重复,将begin更新为hashMap[c] + 1(c字符原位置+1)。更新c下标。


AC Code (C++):

class Solution {
public:
	//981 / 981 test cases passed.
	//Runtime: 99 ms(速度不是很快,不知是不是因为使用了map,亦可不使用map,直接用hash数组)
	int lengthOfLongestSubstring(string s) {
		map<char, int> hashMap;//键为字符,值为字符所在位置
		int maxLength = 0;
		int begin = 0;

		for (int i = 0; i < s.size(); ++i){
			map<char, int>::iterator iter = hashMap.find(s[i]);
			if (hashMap.find(s[i]) != hashMap.end() && iter->second >= begin){//在当前范围内重复出现
				if (maxLength < i - begin){
					maxLength = i - begin;
				}
				begin = iter->second + 1;
			}
			hashMap[s[i]] = i;//更新位置
		}
		if (maxLength < s.size() - begin){
			maxLength = s.size() - begin;
		}

		return maxLength;
	}
};

总结:

hashTable的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值