forked from Wang-Jun-Chao/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest35.java
More file actions
51 lines (45 loc) · 1.54 KB
/
Test35.java
File metadata and controls
51 lines (45 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* Author: 王俊超
* Date: 2015-06-11
* Time: 16:46
* Declaration: All Rights Reserved !!!
*/
public class Test35 {
public static char firstNotRepeatingChar(String s) {
if (s == null || s.length() < 1) {
throw new IllegalArgumentException("Arg should not be null or empty");
}
Map<Character, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
map.put(c, -2);
} else {
map.put(c, i);
}
}
Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
// 记录只出现一次的字符的索引
int idx = Integer.MAX_VALUE;
// 记录只出现一次的字符
char result = '\0';
// 找最小索引对应的字符
for (Map.Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() >= 0 && entry.getValue() < idx) {
idx = entry.getValue();
result = entry.getKey();
}
}
return result;
}
public static void main(String[] args) {
System.out.println(firstNotRepeatingChar("google")); // l
System.out.println(firstNotRepeatingChar("aabccdbd")); // '\0'
System.out.println(firstNotRepeatingChar("abcdefg")); // a
System.out.println(firstNotRepeatingChar("gfedcba")); // g
System.out.println(firstNotRepeatingChar("zgfedcba")); // g
}
}