您的位置:首页 > 其它

LeetCode 003: Longest Substring Without Repeating Characters

2016-05-05 16:43 363 查看

003. Longest Substring Without Repeating Characters

Difficulty: Medium

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.

思路

一开始,是想采用unordered_set容器,可以直接使用它的find操作。

设置变量max记录当前最大长度,初始值为0。

顺序遍历s的字符,使用find操作判断该字符在容器中是否存在;

存在,则先取max和容器元素个数中较大值给max赋值,然后在容器中删除该元素及其前面的所有元素;

向容器添加该元素,不管元素是否存在,都要进行这个操作;

最后s遍历结束,还要比较一次max和容器元素个数的大小,较大值即为最终要得到的值。

但是,使用unordered_set容器会出现问题,原因在于unordered_set容器的元素是存放在bucket中(具体怎么存放不清楚,而且LeetCode和自己用VS的存放方式貌似还不太一样)。

总之,使用迭代器iterator 遍历unordered_set容器中的元素时,该序列与元素插入顺序是不相符的,元素的删除就有误。

因此,放弃使用关联容器,使用顺序容器代替(在这用deuqe),find函数由algorithm.h头文件提供。

代码

[c++]

class Solution {
public:
int lengthOfLongestSubstring(string s) {
deque<char> mydeque;
int max = 0;
for (int i = 0; i < s.length(); ++i) {
deque<char>::iterator it = find(mydeque.begin(), mydeque.end(), s[i]);
if (it != mydeque.end()) {
max = mydeque.size() > max ? mydeque.size() : max;
mydeque.erase(mydeque.begin(), it + 1);
}
mydeque.push_back(s[i]);
}
max = mydeque.size() > max ? mydeque.size() : max;
return max;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: