Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Solution {
  6. static class Node {
  7. char c;
  8. int freq;
  9. public Node(char c, int freq) {
  10. this.c = c;
  11. this.freq = freq;
  12. }
  13. }
  14. public static String rearrange(String str) {
  15. PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>(){
  16. public int compare(Node a, Node b) {
  17. return b.freq - a.freq;
  18. }
  19. });
  20. String res = "";
  21. int[] vector = new int[26];
  22. for (char c : str.toCharArray()) {
  23. vector[c - 'a']++;
  24. }
  25. for (int i = 0; i < vector.length; i++) {
  26. if (vector[i] > 0) {
  27. pq.offer(new Node((char)(i + 'a'), vector[i]));
  28. }
  29. }
  30. Node prev = new Node('#', -1);
  31. while (!pq.isEmpty()) {
  32. Node cur = pq.poll();
  33. res += cur.c;
  34. if (prev.freq > 0) {
  35. pq.offer(prev);
  36. }
  37. cur.freq--;
  38. prev = cur;
  39. }
  40. if (res.length() != str.length()) return "Not Possible";
  41. return res;
  42. }
  43. public static void main (String[] args) {
  44. //code
  45. Scanner sc = new Scanner(System.in);
  46. int num = sc.nextInt();
  47. sc.nextLine();// skip the line
  48. //for (int i = 0; i < num; i++) {
  49. while (sc.hasNext()) {
  50. System.out.println(rearrange(sc.nextLine()));
  51. }
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement