-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueDay1.java
More file actions
43 lines (33 loc) · 1.03 KB
/
Copy pathQueueDay1.java
File metadata and controls
43 lines (33 loc) · 1.03 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
package queue;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
public class QueueDay1 {
public static void main(String[] args) {
String str = "abcbacdabcdeef"; //aaaac#dddddd#e#f
System.out.println(firstNonRepeatingCharacter(str));
}
// First non-repeating character in a stream
static String firstNonRepeatingCharacter(String str) {
StringBuilder sb = new StringBuilder();
// From a...z
int[] frequency = new int[26];
Queue<Character> q = new LinkedList<>();
for (int i = 0; i < str.length(); i++) {
char chr = str.charAt(i);
q.offer(chr);
// `a` == 97,
frequency[chr - 'a']++;
while (!q.isEmpty() && frequency[q.peek() - 'a'] > 1) {
q.poll();
}
if (q.isEmpty()) {
sb.append('#');
} else {
sb.append(q.peek());
}
}
return sb.toString();
}
}