Given a sorting order string, sort the input string based on the given sorting order string. Ex sorting order string -> dfbcae
Input string -> abcdeeabc
output -> dbbccaaee

法一:Comparable

sample Input:

String order = "dfbcae";
String str = "akbcdeeabc";

Sample Output: dbbccaaeekk

要注意13行,indexOf()没有matched到是return -1, 要把它设为最大

 package SortStringBasedOnAnother;
import java.util.*; public class Solution {
public class Sortable implements Comparable<Sortable> { private Character content;
private int order; public Sortable(char str, String sortingOrder) {
this.content = str;
this.order = sortingOrder.indexOf(str);
if (this.order == -1) this.order = Integer.MAX_VALUE;
} public int compareTo(Sortable another) {
if (this.order > another.order) {
return 1;
} else if (this.order == another.order) {
return 0;
} else {
return -1;
}
} public String toString() {
return String.valueOf(content);
} } public void sort(String order, String str) {
Sortable[] array = new Sortable[str.length()];
for (int i = 0; i < str.length(); i++) {
array[i] = new Sortable(str.charAt(i), order);
}
Collections.sort(Arrays.asList(array)); //Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
} } public static void main(String[] args) {
Solution sol = new Solution();
String order = "dfbcae";
String str = "abcdkkeeabc";
sol.sort(order, str);
}
}

方法二:(Better)counting sort

If taking extra mem in allowed. Take an int array with size same as "sorting order string" that will maintain a count. now iterate the input string & keep on incrementing the corresponding char count in this new array.

记得要用一个queue记录没有在order里面的str的元素

 package SortStringBasedOnAnother;
import java.util.*; public class Solution2 {
public void sort(String order, String str) {
int[] count = new int[order.length()];
Queue<Character> notInOrder = new LinkedList<Character>();
StringBuffer sb = new StringBuffer();
for (int i=0; i<str.length(); i++) {
boolean matched = false;
char cur = str.charAt(i);
for (int j=0; j<order.length(); j++) {
if (cur == order.charAt(j)) {
count[j]++;
matched = true;
break;
}
}
if (!matched) notInOrder.offer(cur);
}
for (int i=0; i<count.length; i++) {
while (count[i] > 0) {
sb.append(order.charAt(i));
count[i]--;
}
}
while (!notInOrder.isEmpty()) {
sb.append(notInOrder.poll());
}
System.out.println(sb.toString());
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution2 sol = new Solution2();
String order = "dfbcae";
String str = "akbcdeeabc";
sol.sort(order, str); } }

12-19行可以用IndexOf替代

             char cur = str.charAt(i);
int index = order.indexOf(cur);
if (index == -1) notInOrder.offer(cur);
else count[index]++;

G面经prepare: Sort String Based On Another的更多相关文章

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

    字符串重新排列,让里面不能有相同字母在一起.比如aaabbb非法的,要让它变成ababab.给一种即可 Greedy: 跟FB面经Prepare task Schedule II很像,记录每个char ...

  2. 791. Custom Sort String - LeetCode

    Question 791. Custom Sort String Solution 题目大意:给你字符的顺序,让你排序另一个字符串. 思路: 输入参数如下: S = "cba" T ...

  3. G面经prepare: Maximum Subsequence in Another String's Order

    求string str1中含有string str2 order的 subsequence 的最小长度 DP做法:dp[i][j]定义为pattern对应到i位置,string对应到j位置时,shor ...

  4. G面经Prepare: Valid Preorder traversal serialized String

    求问下各位大神,怎么判断一个按照Preorder traversal serialized的binary tree的序列是否正确呢?不能deserialize成树比如 A) 9 3 4 # # 1 # ...

  5. Groupon面经Prepare: Sort given a range && Summary: Bucket Sort

    首先是如何sort一个只有0和1的数组,要求inplace. follow up是告诉一个range,如何在O(N)时间内sort好 两个pointer可解 package Sorting; impo ...

  6. G面经prepare: Set Intersection && Set Difference

    求两个sorted数组的intersection e.g. [1,2,3,4,5],[2,4,6] 结果是[2,4] difference 类似merge, 分小于等于大于三种情况,然后时间O(m+n ...

  7. [LeetCode] Custom Sort String 自定义排序的字符串

    S and T are strings composed of lowercase letters. In S, no letter occurs more than once. S was sort ...

  8. 牛客第三场多校 E Sort String

    链接:https://www.nowcoder.com/acm/contest/141/E来源:牛客网 Eddy likes to play with string which is a sequen ...

  9. 791. Custom Sort String

    S and T are strings composed of lowercase letters. In S, no letter occurs more than once. S was sort ...

随机推荐

  1. 如何用Apache TCPMon来截获SOAP消息

    在WebService服务器和客户机之间会传递SOAP消息,有时我们需要得到这些消息以便调试,而Apache的TCPMon可以帮助我们做到这一点.  TCPMon的下载地址在http://ws.apa ...

  2. MySQL 5.6.3

    SHOW VARIABLES LIKE '%version%'; https://dev.mysql.com/doc/refman/5.6/en/explain.html As of MySQL 5. ...

  3. CSS子元素margin-top对于父元素的影响

    父元素的盒子包含一个子元素盒子,给子元素盒子一个垂直外边距margin-top,父元素盒子也会往下走margin-top的值,而子元素和父元素的边距则没有发生变化. html代码如下 <styl ...

  4. CRUD操作 create创建 read读取 update修改 delete删除

    1.注释语法:--,#2.后缀是.sql的文件是数据库查询文件3.保存查询4.在数据库里面 列有个名字叫字段 行有个名字叫记录 CRUD操作:create 创建(添加)read 读取update 修改 ...

  5. 实验三--for语句及分支结构else-if

    本节课学习到的知识点: 1.for语句的表达式的应用与掌握.流程形式. 2.多分支else-if,用来判断真假等. 实验中遇到的问题及解决方法: 这次课的逻辑要求比之前的课要难许多,而且对于一些数学逻 ...

  6. os相关方法总结

    __file__表示当前文件 os.path.dirname表示当前文件所在路径的父路径 os.pardir表示当前文件名 os.path.join表示合并 os.path.abspath表示绝对路径

  7. Eclipse+Qt开发环境设置(Linux和Win)

    文章摘要: Windows,Linux平台下安装使用Eclipse + QT4.4.3开发环境 Windows,Linux新建project时的配置(不使用QT预置项目类型,而是手工配置) 使用Ecl ...

  8. C++ 简单中文敏感词检测工具类

    具体思路: 1->敏感词库,可从数据库读取,也可以从文件加载. 2->将敏感词转化为gbk编码,因为gbk严格按照字符一个字节,汉字两个字节的格式编码,便于容易切分文字段. 3->将 ...

  9. Combine String---hdu5727 &&& Zipper(LCS变形)

    题目链接:http://poj.org/problem?id=2192 http://acm.split.hdu.edu.cn/showproblem.php?pid=5707 http://acm. ...

  10. 一些Perl例程(全部手打并执行过)

    #-1-变量使用,打印#!/usr/local/bin/perl$value=100+30+3+8;print("Value=",$value,"\n"); # ...