您的位置:首页 > 其它

[LeetCode] Longest Substring Without Repeating Characters

2017-09-11 17:39 435 查看

题目

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.

思路

这次的题目如果暴力求解的话,是一个很简单的二重循环的字符串比对,但是我觉得既然是一道算法题,而且是跟字符串比对有关的,那么我觉得肯定有KMP算法、sunday算法这种O(n)级别时间复杂度的解决办法。

我考虑到题目对于子字符串的定义是不会有重复的字符,于是我就基于桶排的思想,记录出现的次数,然后桶里的value是出现的次数,每个至多能出现一次,如果>1就意味着重复了。但是实际上这个出现了一个问题,因为我很难界定子字符串的范围,以及是哪个进行重复,实际上,必须利用两个指针来界定启示的位置,以便于发现重复后进行更改。而且相应的,桶中所放入的value就不能再是counter,而需要是位置,用于发生重复后重新定位字符串的起始位置。

代码

class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() == 0) return 0;
int a[256] = {0};
memset(a, -1, 256*sizeof(int));
int maxLength = 0;
int start = -1;
for (int i = 0; i < s.size(); i++) {
// 最近出现的位置在开始之后,意味着出现重复的,移动开始指针至上次出现该字母的下一个位置
if (a[s[i]] > start) {
start = a[s[i]];
}
// 记录最新出现的位置
a[s[i]] = i;
maxLength = max(maxLength, i - start);
}
return maxLength;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: