最长子串,不包含重复字符-问题

时间:2019-07-01 17:52:30

标签: c++

LeetCode问题3: 给定一个字符串,找到最长子字符串的长度而不重复字符。

我无法通过976/978测试用例

“hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”

我不知道如何解决此问题。我知道它由于在for循环外部的if语句而失败。如果最后一个子字符串没有重复字符,则if语句将更新最大长度,因为它不会被for循环捕获。在这一点上,我等于给定字符串的大小,并且应该是最后一个子字符串的起始位置,但是由于某种原因,左边等于128,这对我来说意义不大。

#include <iostream>
#include <unordered_map>
using namespace std;

int main(){
    string s = "hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789hijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    int i = 0;
    int n = s.size(); 
    int left = 0;
    int maxLength = 0;
    int currLength = 0;
    unordered_map<int,char>hashMap;

    for(i = 0; i < n; i++){
        if(hashMap.find(s[i]) == hashMap.end())
            hashMap[s[i]] = i; 

        else {
            if(hashMap[s[i]] >= left){
                currLength = i - left; 
                if(maxLength < currLength){
                    maxLength = currLength; 
                }
                left = hashMap[s[i]] + 1;
            }
            hashMap[s[i]] = i;
        }
    }
    if(maxLength < i - left){
        maxLength = i - left;
    }

    cout << "Expected = 55" << endl;
    cout << "Actual = " << maxLength;
    return 0; 
}

预期结果为55,实际结果为202

0 个答案:

没有答案