找出字符串中第一个只出现一次的字符

题目描述

找出字符串中第一个只出现一次的字符。输入一个非空字符串,输出第一个只出现一次的字符,如果不存在输出-1

示例1:
输入

asdfasdfo

输出

o

思路:

利用桶排序的思想

import java.util.Scanner;

public class Main

public static String solution(String str) {
if(str == null || "".equals(str)) {
return "-1";
}
int[] arr = new int[256]; // 256个bin
int len = str.length();
for(int i = 0; i < len; i++) {
char c = str.charAt(i);
arr[(int)c]++;
}

for(int i = 0; i < len; i++) {
char c = str.charAt(i);
if(arr[(int)c] == 1) {
return String.valueOf(c);
}
}
return "-1";
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String line = sc.nextLine();
String result = solution(line);
System.out.println(result);
}
sc.close();
}

}