public class Main{
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
while (scanner.hasNext()){
String inputStr = scanner.next();
int[] charAppearsCounterArr = new int[26];
int[] charAppearsIndexArr = new int[26];
char[] inputStrCharArr = inputStr.toCharArray();
for(int i = 0; i
char charTmp = inputStrCharArr[i];
int charCounter = charAppearsCounterArr[charTmp - 97];
charAppearsCounterArr[charTmp - 97] = charCounter + 1;
if(charCounter == 0){
charAppearsIndexArr[charTmp - 97] = i;
}
}
int targetChar = -1;
for(int i = 0; i
if(charAppearsCounterArr[i] == 1){
if(targetChar >= 0){
if(charAppearsIndexArr[targetChar] > charAppearsIndexArr[i]){
targetChar = i;
}
}else {
targetChar = i;
}
}
}
if(targetChar >= 0){
System.out.println((char)(targetChar + 97));
}else {
System.out.println("-1");
}
}
}
}
博客给出一段Java代码,用于找出字符串中只出现一次的字符。代码通过扫描输入字符串,统计每个字符的出现次数和首次出现索引,最后找出首次出现且只出现一次的字符并输出,若不存在则输出 -1。

460

被折叠的 条评论
为什么被折叠?



