九度 1530:最长不重复子串

题目描述:

最长不重复子串就是从一个字符串中找到一个连续子串,该子串中任何两个字符都不能相同,且该子串的长度是最大的。

思路

Leetcode 原题

设置两个游标, 右边游标向右走, 出现重复字符时, 左边的游标向右走

代码

#include <iostream>
#include <stdio.h>
#include <memory.h>
using namespace std;

int myHash[30];
char arr[10010];

int main() {
    

    while(scanf("%s", arr) != EOF) {
        memset(myHash, 0, sizeof(myHash));
        int len = strlen(arr);
        int lastpos = 0, global = 0, local = 0;
        for(int i = 0; i < len; i ++) {
            int key = arr[i]-'a';
            myHash[key] ++;
            if(myHash[key] == 2) {
                global = max(global, local);
                for(; lastpos < i && arr[lastpos] != arr[i]; lastpos++) {
                    myHash[arr[lastpos]-'a']--;
                }
                local = i - lastpos;
                myHash[key]--;
                lastpos++;
            }else{
                local ++;
            }
        }
        global = max(global, local);
        cout << global << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xinsheng/p/3580186.html