日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

G面经prepare: Reorder String to make duplicates not consecutive

發(fā)布時(shí)間:2025/6/15 编程问答 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 G面经prepare: Reorder String to make duplicates not consecutive 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
字符串重新排列,讓里面不能有相同字母在一起。比如aaabbb非法的,要讓它變成ababab。給一種即可

Greedy:

跟FB面經(jīng)Prepare task Schedule II很像,記錄每個(gè)char出現(xiàn)次數(shù),然后用最大堆,把剩下char里面出現(xiàn)次數(shù)多的優(yōu)先Poll出來(lái)組建新的string

如果poll出來(lái)的char跟上一個(gè)相同,則用一個(gè)queue暫時(shí)存一下

我覺(jué)得時(shí)間復(fù)雜度: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 }

?

總結(jié)

以上是生活随笔為你收集整理的G面经prepare: Reorder String to make duplicates not consecutive的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。