博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
G面经prepare: Reorder String to make duplicates not consecutive
阅读量:4505 次
发布时间:2019-06-08

本文共 2410 字,大约阅读时间需要 8 分钟。

字符串重新排列,让里面不能有相同字母在一起。比如aaabbb非法的,要让它变成ababab。给一种即可

Greedy:

跟很像,记录每个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
queue = new PriorityQueue
(11, new Comparator
() {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
store = new LinkedList
();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 res50 store.offer(cur);51 }52 }53 else { //store is not empty but queue is empty54 res = new StringBuffer();55 res.append(-1);56 return res.toString();57 }58 }59 return res.toString();60 }61 62 63 /**64 * @param args65 */66 public static void main(String[] args) {67 // TODO Auto-generated method stub68 Solution sol = new Solution();69 String res = sol.reorder("aaabbba");70 System.out.println(res);71 }72 73 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/5140969.html

你可能感兴趣的文章
如何面对客户的紧急需求
查看>>
【转载】嵌入式linux学习规划
查看>>
[转帖]和机器学习和计算机视觉相关的数学
查看>>
mp4格式(转帖加修改) 转载
查看>>
JAVA类加载和初始化
查看>>
SMTP发送邮件
查看>>
关于句柄
查看>>
java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileItemFactory
查看>>
Vue学习之路第十七篇:全局过滤器的使用
查看>>
Http传输Header解释
查看>>
BZOJ4893 项链分赃
查看>>
PIE SDK算法的异步调用
查看>>
deque双向队列
查看>>
Java 环境变量设置
查看>>
Android启动过程_大致流程
查看>>
这么说吧,java线程池的实现原理其实很简单
查看>>
Windows Phone 7, Hammock, OAuth and Sina Weibo’s API
查看>>
【MBN简介】
查看>>
Java进程CPU高
查看>>
Java回调机制
查看>>