leetcode 3.无重复字符的最长子串 C++

思路

用到的东西和第一题比较像,使用的是unordered_map,以此保证复杂度为O(n);
用check依次查找每个字符,如果unordered_map中未找到该字符则存入;若找到则检测最大数max是否小于当前计数count并改动,unordered_map清空,并重开头的指针下一位进行新的查找。

但不知为何提交时其输入"amqpcsrumjjufpu"会报错,我使用的时候并没有。。。
如果有大佬知道原因请指出来,非常感谢!

代码(自用与leetcode提交两种)

#include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char, int> hash;
        char* p;
        char check;
        p = &s[0];
        check = *(p + 1);
        char* p_max = p;
        int count = 0;
        int max = 0;
        if ((*p) != '\0') {
            count = 1;
            max = 1;
            hash[*p] = 1;
        }
        while ((*p) != '\0') {
            if (hash.find(check) == hash.end()&&check != '\0') {
            //判断unordered_map中是否有该字母以及check是否到头
                hash[check] = 1;
                count++;
                check = *(p + count);
            }
            else {
                if (count > max) {
                    max = count;
                    p_max = p;
                }
                count = 1;
                hash.clear();
                p = p + 1;
                hash[*p] = 1;
                check = *(p + 1);
            }
        }
        cout << max << endl;
        return 0;
    }
};
int main()
{
    Solution S;
    string s;
    cin >> s;
    S.lengthOfLongestSubstring(s);
    return 0;
`}

```cpp
//leetcode
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char, int> hash;
        char* p;
        char check;
        p = &s[0];
        check = *(p+1);
        char* p_max = p;
        int count = 0;
        int max = 0;
        if ((*p)!='\0') {
            count = 1;
            max = 1;
            hash[*p] = 1;
        }
        while ((*p)!='\0') {
            if (hash.find(check) == hash.end()&&check!='\0') {
                hash[check] = 1;
                count++;
                check = *(p + count);
                }
                else {
                    if (count > max) {
                        max = count;
                        p_max = p;
                        }
                        count = 1;
                        hash.clear();
                        p = p + 1;
                        hash[*p] = 1;
                        check = *(p + 1);
                    }
            }
            return max;
            }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值