LeetCode3. Longest Substring Without Repeating Characters

本文提供LeetCode第3题“无重复字符的最长子串”的两种解法,一种为O(n²)复杂度,另一种则更为高效,仅使用O(n)的时间复杂度。文章详细解析了每种方法的实现过程。

LeetCode3. Longest Substring Without Repeating Characters

题目:

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.

题目分析 :一看到题目,第一时间想到的就是用set,但是觉得用set还不如直接用一个a[256]的数组。然后用一个max来记录最大长度,然后用了O(n^2)的时间复杂度来实现。

自己的代码:

class Solution {
public:
	int lengthOfLongestSubstring(string s) {
		//set<char> tset;
		if (s.empty()) return 0;
		int tmax = 1;
		int i, j;
		for (i = 0; i < s.size() - 1 - tmax + 1; i++) {
			char a[257] = { 0 };
			a[s[i]] = 1;
			for (j = i + 1; j < s.size(); j++) {
				if (a[s[j]] == 0) {
					a[s[j]]++;
				}
				else {
					tmax = tmax > j - i ? tmax : j - i;
					break;
				}
			}
			int size = 0;
			for (int k = 0; k < 256; k++) {
				if (a[k]) size++;
			}
			tmax = tmax > size ? tmax : size;
		}
		//tmax = tmax > tset.size() ? tmax : tset.size();
		return tmax;
	}
};


但是觉得自己的复杂度有点高,看了一下别人的算法,只用了O(n)的时间复杂度。


代码如下:

int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);
        int maxLen = 0, start = -1;
        for (int i = 0; i != s.length(); i++) {
            if (dict[s[i]] > start)
                start = dict[s[i]];
            dict[s[i]] = i;
            maxLen = max(maxLen, i - start);
        }
        return maxLen;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值