4106:出现两次的字符-Characters Appearing twice
-
总时间限制:
- 1000ms 内存限制:
- 65536kB
-
描述
-
给定一个字符串,求字符串中恰好出现2次的第一个字符。
输入
-
第一行是一个正整数n(int范围),表示共有n个字符串。
下面n行,每行是一个字符串,字符串的长度在int范围内。字符串由小写字母,大写字母和数字构成,不包含其他字符。
输出
- 总共n行,每行输出一个字符,该字符在对应的字符串中恰好出现2次(区分大小写)。如果有多个字符出现2次,输出在字符串中比较靠前的字符。输入数据保证每个字符串中必定有恰好出现2次的字符。 样例输入
-
3
-
farewell
-
20150106
-
PekingUniversity
样例输出
-
e1e
题目问的很直接,练习使用java中的ArrayList类,用到的方法是:
boolean | add(E e)
Appends the specified element to the end of this list.
|
boolean | contains(Object o)
Returns
true if this list contains the specified element.
|
E | get(int index)
Returns the element at the specified position in this list.
|
int | indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
|
boolean | isEmpty()
Returns
true if this list contains no elements.
|
import java.util.*;
//http://bailian.openjudge.cn/practice/4106/
public class CharactersAppearingTwice {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
int n = input.nextInt();
while( n!=0 ){
n--;
String s = input.next();
List<Character> q = new ArrayList<Character>();
int[] count = new int[s.length()];
Arrays.fill(count, 0);
int k = 0;
for( int i = 0 ; i < s.length() ; i++){
if( q.isEmpty() ){
q.add(s.charAt(i));
count[k]++;
k++;
}else if( q.contains(s.charAt(i))){
int index = q.indexOf(s.charAt(i));
count[index]++;
}else{
q.add(s.charAt(i));
count[k]++;
k++;
}
}
for( int i = 0 ; i < k ; i++){
char c = q.get(i);
if( count[i] == 2 ){
System.out.println(c);
break;
}
}
}
}
}