G面经prepare: Reorder String to make duplicates not consecutive
生活随笔
收集整理的這篇文章主要介紹了
G面经prepare: Reorder String to make duplicates not consecutive
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字符串重新排列,讓里面不能有相同字母在一起。比如aaabbb非法的,要讓它變成ababab。給一種即可
Greedy:
跟FB面經Prepare task Schedule II很像,記錄每個char出現次數,然后用最大堆,把剩下char里面出現次數多的優先Poll出來組建新的string
如果poll出來的char跟上一個相同,則用一個queue暫時存一下
我覺得時間復雜度:O(N) + O(KlogK) + O(NlogK) = O(NlogK) ,where K is the number of different character in the string
1 package ReorderString; 2 import java.util.*; 3 4 public class Solution { 5 class Element { 6 char val; 7 int appear; 8 public Element(char value) { 9 this.val = value; 10 this.appear = 1; 11 } 12 } 13 14 public String reorder(String str) { 15 Element[] summary = new Element[26]; 16 for (int i=0; i<str.length(); i++) { 17 char cur = str.charAt(i); 18 if (summary[(int)(cur-'a')] == null) { 19 summary[(int)(cur-'a')] = new Element(cur); 20 } 21 else { 22 summary[(int)(cur-'a')].appear++; 23 } 24 } 25 PriorityQueue<Element> queue = new PriorityQueue<Element>(11, new Comparator<Element>() { 26 public int compare(Element e1, Element e2) { 27 return e2.appear - e1.appear; 28 } 29 }); 30 31 for (Element each : summary) { 32 if (each != null) { 33 queue.offer(each); 34 } 35 } 36 Queue<Element> store = new LinkedList<Element>(); 37 StringBuffer res = new StringBuffer(); 38 while (!queue.isEmpty() || !store.isEmpty()) { 39 if (!queue.isEmpty()) { 40 Element cur = queue.poll(); 41 if (res.length()==0 || cur.val!=res.charAt(res.length()-1)) { 42 res.append(cur.val); 43 cur.appear--; 44 if (cur.appear > 0) store.offer(cur); 45 while (!store.isEmpty()) { 46 queue.offer(store.poll()); 47 } 48 } 49 else { //cur.val equals last char in res 50 store.offer(cur); 51 } 52 } 53 else { //store is not empty but queue is empty 54 res = new StringBuffer(); 55 res.append(-1); 56 return res.toString(); 57 } 58 } 59 return res.toString(); 60 } 61 62 63 /** 64 * @param args 65 */ 66 public static void main(String[] args) { 67 // TODO Auto-generated method stub 68 Solution sol = new Solution(); 69 String res = sol.reorder("aaabbba"); 70 System.out.println(res); 71 } 72 73 }?
總結
以上是生活随笔為你收集整理的G面经prepare: Reorder String to make duplicates not consecutive的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SimpleDateFormat使用详解
- 下一篇: 目标检测之dpm---hog的最优升级版