Find the longest non-repeated character substring of the string

Find the longest non-repeated character substring of the string

Title description

Given an array arr, return the length of the longest repeating substring of arr (no repeating means that all letters are different).

Enter a description:

The input contains two lines, the first line contains an integer n (1 ≤ n ≤ 1 0 5) n(1 \leq n \leq 10^5)n(1n105 ), representing the length of the array arr, the second line contains n integers, representing the arrayarr (1 ≤ arr [i] ≤ 1 0 6) arr(1 \leq arr[i] \leq 10^6)arr(1arr[i]106)

Output description:

Output an integer, representing the length of the longest non-repeated character of arr.

Example 1
enter
4
2 3 4 5
Output
4
Example 2
enter
5
2 2 3 4 3
Output
3

answer:

greedy. Use a hash table to record the most recent position of each element. Assuming that the current traversal to position i, pre indicates the position before the start of the longest non-repeated substring under the condition that it must end with arr[i-1]. If pre<hash[arr[i]], indicating that arr[i] appears after pre, then update pre to hash[arr[i]]; otherwise, the positions from pre+1 to i are non-repeated elements, Just update the maximum length directly.

Code:
#include <cstdio>

using namespace std;

const int N = 1000010;

int n;
int a[N];

int main(void) {
    
    
    scanf("%d", &n);
    int pre = 0, ret = 0;
    int val;
    for (int i = 0; i < n; ++i) {
    
    
        scanf("%d", &val);
        if (!a[val] || a[val] < pre) {
    
    
            if (i - pre + 1 > ret) ret = i - pre + 1;
        } else pre = a[val];
        a[val] = i + 1;
    }
    return 0 * printf("%d\n", ret);
}

Guess you like

Origin blog.csdn.net/MIC10086/article/details/108952029