fork download
  1. import java.util.*;
  2.  
  3. class Main {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6.  
  7. String s = sc.nextLine();
  8.  
  9. int[] freq = new int[26];
  10. Queue<Character> q = new LinkedList<>();
  11. StringBuilder ans = new StringBuilder();
  12.  
  13. for (char ch : s.toCharArray()) {
  14.  
  15. // Count frequency
  16. freq[ch - 'a']++;
  17.  
  18. // Add current character to queue
  19. q.offer(ch);
  20.  
  21. // Remove characters that are repeating
  22. while (!q.isEmpty() && freq[q.peek() - 'a'] > 1) {
  23. q.poll();
  24. }
  25.  
  26. // First non-repeating character
  27. if (q.isEmpty()) {
  28. ans.append('#');
  29. } else {
  30. ans.append(q.peek());
  31. }
  32. }
  33.  
  34. System.out.println(ans);
  35. }
  36. }
Success #stdin #stdout 0.12s 56628KB
stdin
aabc
stdout
a#bb