-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstNonRepeatingCharacterStream.java
More file actions
38 lines (31 loc) · 1.14 KB
/
FirstNonRepeatingCharacterStream.java
File metadata and controls
38 lines (31 loc) · 1.14 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
import java.util.*;
public class FirstNonRepeatingCharacterStream {
public static String firstNonRepeating(String s) {
int[] freq = new int[26]; // Frequency of each character
Queue<Character> q = new LinkedList<>(); // Queue to maintain stream order
StringBuilder result = new StringBuilder();
for (char ch : s.toCharArray()) {
freq[ch - 'a']++; // Increment frequency
q.add(ch); // Add to queue
// Remove repeated characters from the front
while (!q.isEmpty() && freq[q.peek() - 'a'] > 1) {
q.poll();
}
// Append result
if (q.isEmpty()) {
result.append('#');
} else {
result.append(q.peek());
}
}
return result.toString();
}
public static void main(String[] args) {
// Example 1
String s1 = "aabc";
System.out.println(firstNonRepeating(s1)); // Output: a#bb
// Example 2
String s2 = "zz";
System.out.println(firstNonRepeating(s2)); // Output: z#
}
}