5. Find the first character in the string that only appears once
Enter description:
输入几个非空字符串
Output description
输出第一个只出现一次的字符,如果不存在输出-1
Example
enter
asdfasdfo
aabb
Output
o
-1
analysis
1. Key in a character string
2. If a character string is searched from front to back and from back to front, the same one is found, then it can be determined that this character only appears once. This is the ingenious place of this question! Nothing else! , That's too clever
Code
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main5 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
while ((str = br.readLine()) != null) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (str.indexOf(c) == str.lastIndexOf(c)) {
System.out.println(c);
break;
}
if (i == str.length() - 1)
System.out.println("-1");
}
}
}
}