G面经prepare: Sort String Based On Another

时间:2023-12-12 17:16:38
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]++;