Leetcode题解 - 3. Longest Substring Without Repeating Characters

本文介绍了一种解决最长无重复字符子串问题的有效算法,通过迭代检查字符并更新子串,实现快速查找。提供了两种不同优化级别的C++实现方案。

摘要生成于 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.


思路

1. 使用一个临时字符串存放子串T
2. 每次从输入中获取一个字符C,并检查已有的子串T中是否已经存在该字符
    - 如果存在,删除该字符之前的所有字符和它自己
3. 将C追加在子串T的尾部
4. 获取子串T的长度,并决定是否要更新最大值MAX
5. 重复1~4步骤,直到输入的所有的字符都处理完
6. 返回最大值MAX


本人的解

根据上述思路,代码如下。耗时29毫秒。

class Solution {
public:
	/* 29 ms, Your runtime beats 51.30% of cpp submissions */
	int lengthOfLongestSubstring(string s) {
		int max = 0;
		string t("");
		for( int i = 0; i < s.length(); i++ ) {
			size_t pos = t.find(s[i], 0);
			if( pos != string::npos ) t.erase(0, pos + 1);
			t.append(1, s[i]);
			if( t.length() > max ) max = t.length();
		}
		return max;
	}
};

改进版。
由于题目要求返回长度,而不是子字符串。所以可以使用string::back()函数取最后一个字符,处理完后使用string::pop_back()删除最后一个字符。
改进后,耗时12毫秒,算是比较快的了。

class Solution {
public:
	/* 12 ms, Your runtime beats 87.44% of cpp submissions */
	int lengthOfLongestSubstring(string s) {
		int max = 0;
		string t("");
		while( s.length() ) {
			char a = s.back();
			size_t pos = t.find(a, 0);
			if( pos != string::npos ) t.erase(0, pos + 1);
			t.append(1, a);
			if( t.length() > max ) max = t.length();
			s.pop_back();
		}
		return max;
	}
};










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值