Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.*;
- import java.io.*;
- class Solution {
- static class Node {
- char c;
- int freq;
- public Node(char c, int freq) {
- this.c = c;
- this.freq = freq;
- }
- }
- public static String rearrange(String str) {
- PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>(){
- public int compare(Node a, Node b) {
- return b.freq - a.freq;
- }
- });
- String res = "";
- int[] vector = new int[26];
- for (char c : str.toCharArray()) {
- vector[c - 'a']++;
- }
- for (int i = 0; i < vector.length; i++) {
- if (vector[i] > 0) {
- pq.offer(new Node((char)(i + 'a'), vector[i]));
- }
- }
- Node prev = new Node('#', -1);
- while (!pq.isEmpty()) {
- Node cur = pq.poll();
- res += cur.c;
- if (prev.freq > 0) {
- pq.offer(prev);
- }
- cur.freq--;
- prev = cur;
- }
- if (res.length() != str.length()) return "Not Possible";
- return res;
- }
- public static void main (String[] args) {
- //code
- Scanner sc = new Scanner(System.in);
- int num = sc.nextInt();
- sc.nextLine();// skip the line
- //for (int i = 0; i < num; i++) {
- while (sc.hasNext()) {
- System.out.println(rearrange(sc.nextLine()));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement