(1)方法1
使用HashSet
public void test1() {
String str ="abccba";
Character repeatCharacter=null;
Set<Character> set=new HashSet<Character>();
for (int i = 0; i < str.length(); i++) {
if (!set.add(str.charAt(i))) {
repeatCharacter=str.charAt(i);
break;
}
}
System.out.println("第一次重复出现的字符:"+repeatCharacter);
}
(2)方法2
使用HashMap
public void test2() {
String str ="abccba";
Character repeatCharacter=null;
Map<Character,Integer> map=new HashMap<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
char c=str.charAt(i);
/*Integer count = map.get(c);
if (count==null) {
map.put(c,1);
} else if (count==1) {
repeatCharacter=c;
break;
}*/
if (map.containsKey(c)) {
repeatCharacter=str.charAt(i);
break;
} else {
map.put(c,1);
}
}
System.out.println("第一次重复出现的字符:"+repeatCharacter);
}