โจทย์: หา First Non-Repeating Character ใน Stream
อ่าน character ทีละตัว แสดงตัวแรกที่ยังไม่ซ้ำ ณ จุดนั้น (Streaming algorithm)
ตัวอย่างโค้ด (ปรับปรุง: ใช้ Queue + Count Array)
import java.util.*;
public class Demo {
static final int MAX_CHAR = 256; // ASCII
public static void firstNonRepeatingStream(String stream) {
int[] count = new int[MAX_CHAR];
Queue queue = new LinkedList<>();
System.out.println("Stream: " + stream);
System.out.print("Output: ");
for (char ch : stream.toCharArray()) {
// เพิ่ม character เข้า queue
queue.add(ch);
count[ch]++;
// ลบตัวซ้ำจากหน้าคิว
while (!queue.isEmpty() && count[queue.peek()] > 1) {
queue.poll();
}
// แสดงผล
if (!queue.isEmpty()) {
System.out.print(queue.peek() + " ");
} else {
System.out.print("-1 ");
}
}
System.out.println();
}
public static void main(String[] args) {
firstNonRepeatingStream("aabcbc");
// Output: a -1 b b c -1
firstNonRepeatingStream("Thisisasample");
}
}
ผลลัพธ์
Stream: aabcbc Output: a -1 b b c -1 Stream: Thisisasample Output: T T T T T T T T T T T T T
คำอธิบาย:
- Queue เก็บ candidates ที่ยังไม่ซ้ำ (เรียงตามลำดับมาถึง)
- Count array นับ frequency
- ทุกครั้งที่เพิ่ม char ใหม่: เพิ่มใน queue, increment count, แล้ว pop หน้าคิวจนกว่าจะเจอตัวที่ count==1
- Time: O(n) ต่อ character (amortized) - แต่ละ char เข้า/ออก queue สูงสุด 1 ครั้ง
- Space: O(1) - count array 256 + queue max 256
เวอร์ชันเดิมในโจทย์ (มี bug: พิมพ์ซ้ำทุก loop)
โค้ดต้นฉบับพิมพ์ผลลัพธ์ ภายใน loop ทำให้ output ซ้ำ ใช้ Queue approach ข้างต้นดีกว่า