1. 程式人生 > 其它 >找到字串的最長無重複字元子串

找到字串的最長無重複字元子串

連結

給定一個數組arr,返回arr的最長無的重複子串的長度(無重複指的是所有字母都不相同)。

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            int[] arr = new int[n];
            for (int i = 0; i < n; ++i) {
                arr[i] = in.nextInt();
            }
            Map<Integer, Integer> hash = new HashMap<>();
            int ret = 0;
            int pre = 0;
            for (int i = 0; i < n; ++i) {
                Integer index = hash.get(arr[i]);
                if (index == null) {
                    pre = pre + 1;
                } else {
                    pre = Math.min(i - index, pre + 1);
                }
                hash.put(arr[i], i);
                ret = Math.max(ret, pre);
            }
            System.out.println(ret);
        }
    }
}
心之所向,素履以往 生如逆旅,一葦以航