字符串重新排列,让里面不能有相同字母在一起。比如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

 package ReorderString;
import java.util.*; public class Solution {
class Element {
char val;
int appear;
public Element(char value) {
this.val = value;
this.appear = 1;
}
} public String reorder(String str) {
Element[] summary = new Element[26];
for (int i=0; i<str.length(); i++) {
char cur = str.charAt(i);
if (summary[(int)(cur-'a')] == null) {
summary[(int)(cur-'a')] = new Element(cur);
}
else {
summary[(int)(cur-'a')].appear++;
}
}
PriorityQueue<Element> queue = new PriorityQueue<Element>(11, new Comparator<Element>() {
public int compare(Element e1, Element e2) {
return e2.appear - e1.appear;
}
}); for (Element each : summary) {
if (each != null) {
queue.offer(each);
}
}
Queue<Element> store = new LinkedList<Element>();
StringBuffer res = new StringBuffer();
while (!queue.isEmpty() || !store.isEmpty()) {
if (!queue.isEmpty()) {
Element cur = queue.poll();
if (res.length()==0 || cur.val!=res.charAt(res.length()-1)) {
res.append(cur.val);
cur.appear--;
if (cur.appear > 0) store.offer(cur);
while (!store.isEmpty()) {
queue.offer(store.poll());
}
}
else { //cur.val equals last char in res
store.offer(cur);
}
}
else { //store is not empty but queue is empty
res = new StringBuffer();
res.append(-1);
return res.toString();
}
}
return res.toString();
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution sol = new Solution();
String res = sol.reorder("aaabbba");
System.out.println(res);
} }

最新文章

  1. mysql存储过程学习
  2. 人脸识别必读的N篇文章
  3. iframe仿Ajax上传文件
  4. C++ static(施工中)
  5. SQL Server 中的SET XACT_ABORT各种用法及显示结果
  6. 解决div里面img的缝隙问题~
  7. 习惯使用断言Assert
  8. 深入浅出—JAVA(6)
  9. Flexible 弹性盒子模型之CSS align-self 属性
  10. 使用Libgdx开发的FlappyBird(像素鸟、疯狂的小鸟)游戏源码
  11. nginx 安装php
  12. .NET HttpPost 上传文件图片到服务器
  13. java常见3种文件上传速度对比和文件上传方法详细代码
  14. Spring Boot中使用AOP统一处理Web请求日志
  15. Rest Client插件简单介绍
  16. ubuntu gnome桌面隐藏顶栏
  17. auto sudo password in shell
  18. CentOS7系列--1.4CentOS7服务
  19. win7 64位mysql安装及navicat 解压版
  20. Google Map 学习过程中的代码

热门文章

  1. mysql-insert-返回主键id
  2. linux 输入java 出现中文乱码
  3. 转一个 C#基础类库
  4. ecshop换用redis做缓存
  5. 大数据下的java client连接JDBC
  6. javascript === 与 ==
  7. MySQL &#183; 性能优化 &#183; 条件下推到物化表
  8. 禁用LMHOSTS和NetBIOS后提升上网速度 ?
  9. K线指标线计算方法
  10. css实现元素居中