找到字串的最長無重複字元子串
阿新 • • 發佈:2021-10-19
給定一個數組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); } } }