HashSet的应用实例

HashSet的一个应用实例,笔试题:

对于一个字符串,请设计一个高效算法,找到第一次重复出现的字符。
给定一个字符串(不一定全为字母)A及它的长度n。请返回第一个重复出现的字符。保证字符串中有重复字符,字符串的长度小于等于500。
测试样例:
“hjhfjdshfj”,10
返回:y

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Soluction{
public static char findFirstRepeat(String A, int n){
char [] a = A.toCharArry();
HashSet hs = new HashSet<>();
for(int i = 0;i<n;i++){
if(!hs.add(a[i])){
return a[i];
}
}
return 0;

}
public static void main(String[] args){
System.out.println(findFirstRepeat("asdfsfsd",11))
}
}