----------------------------------------------本题链接----------------------------------------------
题目描述
给定一个数组arr,返回arr的最长无的重复子串的长度(无重复指的是所有数字都不相同)。
示例
输入
1: [2,3,4,5]
2: [2,2,3,4,3]
返回值
1: 4
2: 3
思路
哈希集+双指针
用hashmap对重复数字进行记录和判断,双指针记录子串开始和结束位置
出现重复数字,判断前一个重复数字位置(可能在start前面,所以需要用max函数),随后移动start
算法过程
- 判断异常情况
- 初始化hashmap
- 双指针判断子串
- 输出结果
解答
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
if(arr.length < 2) return arr.length;
HashMap<Integer, Integer> map = new HashMap<>();
int res = 1;
for(int start = 0, end = 0; end < arr.length; end++){
if(map.containsKey(arr[end])){
start = Math.max(start, map.get(arr[end])+1);
}
res = Math.max(res, end - start+1);
map.put(arr[end], end);
}
return res;
}
}