题目:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。
代码如下:
import java.util.Scanner;
public class Test2 {
public static char first(String s) { char result = '0'; char t; int num[] = new int[50]; for (int i = 0; i < s.length(); i ++) { t = s.charAt(i); if ( t >= 'a' && t <= 'z' ) { num[t - 'a']++; } else if (t >= 'A' && t <= 'Z') { num[t - 'A' + 26] ++; } } for (int i = 0; i < num.length; i ++) { if (num[i] == 1) { if (i >= 0 && i <=26) { result = (char)(i + 'a'); } else result = (char)(i - 26 + 'A'); break; } } return result; } public static void main(String[] args) { System.out.println("请输入字符串:"); Scanner reader = new Scanner(System.in); String s = reader.next(); char c = first(s); System.out.println(c); } }