百炼4106:出现两次的字符-Characters Appearing twice

4106:出现两次的字符-Characters Appearing twice

总时间限制:
1000ms
内存限制:
65536kB
描述

给定一个字符串,求字符串中恰好出现2次的第一个字符。

输入
第一行是一个正整数n(int范围),表示共有n个字符串。
下面n行,每行是一个字符串,字符串的长度在int范围内。字符串由小写字母,大写字母和数字构成,不包含其他字符。
输出
总共n行,每行输出一个字符,该字符在对应的字符串中恰好出现2次(区分大小写)。如果有多个字符出现2次,输出在字符串中比较靠前的字符。输入数据保证每个字符串中必定有恰好出现2次的字符。
样例输入
3
farewell
20150106
PekingUniversity
样例输出
e1e

题目问的很直接,练习使用java中的ArrayList类,用到的方法是:

booleanadd(E e)
Appends the specified element to the end of this list.
booleancontains(Object o)
Returns true if this list contains the specified element.
Eget(int index)
Returns the element at the specified position in this list.
intindexOf(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.
booleanisEmpty()
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;
				}
			}
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值