LeetCode 003: Longest Substring Without Repeating Characters

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值