解题思路:通过两个指针分别指向子串的头尾,并将出现过的字符以及最新一次出现的位置存入hash表中。当尾指针所指字符在hash表中,则改变头指针位置;否则,只向后移动尾指针。
import java.util.*;
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
// write code here
HashMap<Integer,Integer> mp=new HashMap<>();
int max=0;
int n=1;
if(arr.length==1){
return 1;
}
int i=0;
mp.put(arr[0],0);
for(int j=1;j<arr.length;j++){
if(mp.containsKey(arr[j])){
i=Math.max(i,mp.get(arr[j])+1);
mp.replace(arr[j],j);
max=Math.max(max,n);
n=j-i+1;
}
else{
mp.put(arr[j],j);
n++;
}
}
return Math.max(max,n);
}
}
京公网安备 11010502036488号