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;
            }
};
发布了9 篇原创文章 · 获赞 1 · 访问量 157

猜你喜欢

转载自blog.csdn.net/qq_37782336/article/details/104449405