G面经prepare: Sort String Based On Another

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, 要把它设为最大

 1 package SortStringBasedOnAnother;
 2 import java.util.*;
 3
 4 public class Solution {
 5     public class Sortable implements Comparable<Sortable> {
 6
 7         private Character content;
 8         private int order;
 9
10         public Sortable(char str, String sortingOrder) {
11             this.content = str;
12             this.order = sortingOrder.indexOf(str);
13             if (this.order == -1) this.order = Integer.MAX_VALUE;
14         }
15
16         public int compareTo(Sortable another) {
17             if (this.order > another.order) {
18                 return 1;
19             } else if (this.order == another.order) {
20                 return 0;
21             } else {
22                 return -1;
23             }
24         }
25
26         public String toString() {
27             return String.valueOf(content);
28         }
29
30     }
31
32     public void sort(String order, String str) {
33         Sortable[] array = new Sortable[str.length()];
34         for (int i = 0; i < str.length(); i++) {
35             array[i] = new Sortable(str.charAt(i), order);
36         }
37         Collections.sort(Arrays.asList(array)); //Arrays.sort(array);
38         for (int i = 0; i < array.length; i++) {
39             System.out.print(array[i]);
40         }
41
42     }
43
44     public static void main(String[] args) {
45             Solution sol = new Solution();
46             String order = "dfbcae";
47             String str = "abcdkkeeabc";
48             sol.sort(order, str);
49     }
50 }

方法二:(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的元素

 1 package SortStringBasedOnAnother;
 2 import java.util.*;
 3
 4 public class Solution2 {
 5     public void sort(String order, String str) {
 6         int[] count = new int[order.length()];
 7         Queue<Character> notInOrder = new LinkedList<Character>();
 8         StringBuffer sb = new StringBuffer();
 9         for (int i=0; i<str.length(); i++) {
10             boolean matched = false;
11             char cur = str.charAt(i);
12             for (int j=0; j<order.length(); j++) {
13                 if (cur == order.charAt(j)) {
14                     count[j]++;
15                     matched = true;
16                     break;
17                 }
18             }
19             if (!matched) notInOrder.offer(cur);
20         }
21         for (int i=0; i<count.length; i++) {
22             while (count[i] > 0) {
23                 sb.append(order.charAt(i));
24                 count[i]--;
25             }
26         }
27         while (!notInOrder.isEmpty()) {
28             sb.append(notInOrder.poll());
29         }
30         System.out.println(sb.toString());
31     }
32
33
34     /**
35      * @param args
36      */
37     public static void main(String[] args) {
38         // TODO Auto-generated method stub
39         Solution2 sol = new Solution2();
40         String order = "dfbcae";
41         String str = "akbcdeeabc";
42         sol.sort(order, str);
43
44     }
45
46 }

12-19行可以用IndexOf替代

1             char cur = str.charAt(i);
2             int index = order.indexOf(cur);
3             if (index == -1) notInOrder.offer(cur);
4             else count[index]++;
时间: 2024-10-19 09:43:21

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

791. Custom Sort String - LeetCode

Question 791. Custom Sort String Solution 题目大意:给你字符的顺序,让你排序另一个字符串. 思路: 输入参数如下: S = "cba" T = "abcd" 先构造一个map,sMap key存储S中出现的字符,value存储字符在S中的位置 c -> 0 b -> 1 a -> 2 再构造一个int数组,sIdx sIdx,存储S中的字符在T字符串中出现的次数 遍历T字符串 如果字符在sMap中,sIdx

G面经Prepare: Valid Preorder traversal serialized String

1 求问下各位大神,怎么判断一个按照Preorder traversal serialized的binary tree的序列是否正确呢?不能deserialize成树比如 2 A) 9 3 4 # # 1 # # 2 # 6 # #是对的,因为表示 3 9 4 / 5 3 2 6 / \ 7 4 1 6 8 B ) 9 3 4 # # 1 # #就是错的,因为无法反构造回一棵树 我觉得可以在字符串里找"n##"这种结构(对应tree里两个children都是Null的叶节点),找到之后

Groupon面经Prepare: Sort given a range &amp;&amp; Summary: Bucket Sort

首先是如何sort一个只有0和1的数组,要求inplace. follow up是告诉一个range,如何在O(N)时间内sort好 两个pointer可解 1 package Sorting; 2 import java.util.*; 3 4 public class InplaceSorting { 5 public void sorting(int[] arr) { 6 if (arr==null || arr.length==0) return; 7 int l=0, r=arr.le

(线段树区间赋值)CSU 1942 - Sort String

题意: 一个串(串中只有26个小写字母),选一个区间进行排序,进行100000次,输出最后的串. 分析: 比赛的时候很懵逼,感觉这题跟之前的额大崩龙有点像,但是没多想,也怪自己太菜了. 确实是真的像,甚至是一模一样啊. 对于每次排序只需要进行一次类似计数排序的的操作即可,26个字符,进行26次区间赋值即可.理论上时间能过得去. 代码: 1 #include <queue> 2 #include <string> 3 #include <cstdio> 4 #includ

G面经Prepare: Print Zigzag Matrix

For instance, give row = 4, col = 5, print matrix in zigzag order like: [1, 8, 9, 16, 17] [2, 7, 10, 15, 18] [3, 6, 11, 14, 19] [4, 5, 12, 13, 20] 1 package GooglePhone; 2 3 import java.util.Arrays; 4 5 public class PrintMatrix { 6 7 static void prin

G面经Prepare: Longest All One Substring

give a string, all 1 or 0, we can flip a 0 to 1, find the longest 1 substring after the flipping 这是一个简单版本of LC 424 Longest Repeating Character Replacement 又是Window, 又是Two Pointers Window还是采用每次都try to update left使得window valid, 每次都检查最大window 1 package

G面经prepare: Friends Recommendation

想想如果你用linkedin或者facebook, 给你一个人和他的朋友关系网,你会怎么给一个人推荐朋友 一个例子就是A-B, A-C, B - D, B - E, C - D,这个时候问我应该推荐谁给A,我说D,因为他是BC的共同好友,而E只是B的好友,到这我才明白干啥,就是给一个图和里面的一个节点A,用bfs从A出发,找出第二层中indegree度数最大节点 用HashMap<Character, HashSet<Character>>来建图 用HashMap<Chara

G面经prepare: Straight Partition of A Deck of Cards

Define “Straight” as 5 cards with consecutive numbers. Determine if the deck can be fully divided into sets of “Straight”. Example: 1, 2, 3, 4, 4, 5, 5, 6, 7, 8 -> True 这个是用一个hashtable,key是数字,value是出现次数 然后遍历原数组,每一个数字都把hash里从自己开始往后5个color数都-1,如果发现缺数则说

G面经prepare: Chucked Palindrome

给定一个字符串,找出最多有多少个chunked palindrome, 正常的palindrome是abccba, chunked palindrome的定义是:比如volvo, 可以把vo划分在一起,(vo) (l) (vo),那么它是个palindrome.求实现返回最大的chunk 数量. 比如aaaaaa可以是(aaa)(aaa), 但是最大chunk数量应该是(a)(a)(a)(a)(a)(a)为6 这就是一个greedy的问题,从string的两边开始,用i和j记录当前scan到的位