forked from Wang-Jun-Chao/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test55.java
69 lines (61 loc) · 2.25 KB
/
Test55.java
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Author: 王俊超
* Date: 2015-06-15
* Time: 14:54
* Declaration: All Rights Reserved !!!
*/
public class Test55 {
/**
* 题目:请实现一个函数用来找出字符流中第一个只出现一次的字符。
*/
private static class CharStatistics {
// 出现一次的标识
private int index = 0;
private int[] occurrence = new int[256];
public CharStatistics() {
for (int i = 0; i < occurrence.length; i++) {
occurrence[i] = -1;
}
}
private void insert(char ch) {
if (ch > 255) {
throw new IllegalArgumentException( ch + "must be a ASCII char");
}
// 只出现一次
if (occurrence[ch] == -1) {
occurrence[ch] = index;
} else {
// 出现了两次
occurrence[ch] = -2;
}
index++;
}
public char firstAppearingOnce(String data) {
if (data == null) {
throw new IllegalArgumentException(data);
}
for (int i = 0; i < data.length(); i++) {
insert(data.charAt(i));
}
char ch = '\0';
// 用于记录最小的索引,对应的就是第一个不重复的数字
int minIndex = Integer.MAX_VALUE;
for (int i = 0; i < occurrence.length; i++) {
if (occurrence[i] >= 0 && occurrence[i] < minIndex) {
ch = (char) i;
minIndex = occurrence[i];
}
}
return ch;
}
}
public static void main(String[] args) {
System.out.println(new CharStatistics().firstAppearingOnce("")); // '\0'
System.out.println(new CharStatistics().firstAppearingOnce("g")); // 'g'
System.out.println(new CharStatistics().firstAppearingOnce("go")); // 'g'
System.out.println(new CharStatistics().firstAppearingOnce("goo")); // 'g'
System.out.println(new CharStatistics().firstAppearingOnce("goog")); // '\0'
System.out.println(new CharStatistics().firstAppearingOnce("googl")); // l
System.out.println(new CharStatistics().firstAppearingOnce("google")); // l
}
}