题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
http://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4
解决方法
1、方法一:统计每个字符出现次数
2、方法二:通过indexOf()和lastIndex)f()判断字符第一次和最后一次出现的下标是否相等
(1)统计字符
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
// 遍历
String ans = "-1";
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (map.get(ch) == 1) {
ans = "" + ch;
break;
}
}
System.out.println(ans);
}
}
(2)比较前后出现字符下标
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
// 遍历
String ans = "-1";
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (line.indexOf(ch) == line.lastIndexOf(ch)) {
ans = "" + ch;
break;
}
}
System.out.println(ans);
}
}