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. jsp页面揣出现Invalid action class configuration that references an unknown class解决方案

    jsp页面中,增加和修改用了同一个页面,能正常增加,却不能修改,后来发现页面中有一个hidden的id, 这个input的name写成name="designType.id"时就会 ...

  2. Flink - FLIP

    https://cwiki.apache.org/confluence/display/FLINK/Flink+Improvement+Proposals FLIP-1 : Fine Grained ...

  3. OpenMP并行编程

    什么是OpenMP?“OpenMP (Open Multi-Processing) is an application programming interface (API) that support ...

  4. [have_fun] 好玩哒小游戏又来啦

    联机贪吃蛇,相互厮杀,试一下吧! http://splix.io/

  5. ubuntu如何开启root,如何启用Ubuntu中root帐号

    jingyan.baidu.com/article/495ba84116104238b20ede62.html ubuntu如何开启root,如何启用Ubuntu中root帐号 | 浏览:8344 | ...

  6. [收藏]Asp.net MVC生命周期

    一个HTTP请求从IIS移交到Asp.net运行时,Asp.net MVC是在什么时机获得了控制权并对请求进行处理呢?处理过程又是怎样的? 以IIS7中asp.net应用程序生命周期为例,下图是来自M ...

  7. GetLogicalProcessorInformation(XP3才支持)和GetLogicalProcessorInformationEx(WIN7才支持)

    https://msdn.microsoft.com/en-us/library/windows/desktop/ms683194(v=vs.85).aspx 例子执行结果如下: https://ms ...

  8. .NET 可空值类型

    Microsoft在CLR中引入了可空值类型(nullable value type)的概念. FCL中定义System.Nullable<T>类如下: [Serializable,Str ...

  9. php日期时间函数 整理

    设定系统默认时区 date_default_timezone_get() $tz='America/Los_Angeles'; 返回系统默认时区 date_default_timezone_set($ ...

  10. Magento PHP Extension "curl" must be loaded解决方法

    我记得我第一次在xampp装magento的时候,进入后台时提示PHP Extension "curl" must be loaded 在网页上查了下原因和解决方法,发现是mage ...