一、题目描述
找出字符串中第一个只出现一次的字符
二、代码实现
使用哈希表:
import java.util.Scanner;
import java.util.Map;
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String input = sc.nextLine();
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
for (int i=0; i<input.length(); i++) {
char ch = input.charAt(i);
if (map.get(ch) == null) {
map.put(ch, 1);
} else {
map.put(ch, map.get(ch)+1);
}
}
char ch = ' ';
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
//System.out.println(entry.getKey());
ch = entry.getKey();
break;
}
}
if (ch == ' ') {
System.out.println(-1);
} else {
System.out.println(ch);
}
}
}
}
暴力法(O(N^2)):
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String input = sc.nextLine();
boolean flag = true;
for (int i=0; i<input.length(); i++) {
char ch = input.charAt(i);
if (input.indexOf(ch) == input.lastIndexOf(ch)) {
System.out.println(ch);
flag = false;
break;
}
}
if (flag) {
System.out.println(-1);
}
}
}
}