问题:
难度:medium
说明:
给出两个字符串,要求将str 字符串按照 order 的相对顺序进行排序,所有的输入字符都是 [a-z]* ,然后不在 order 字符集的 str 字符就按照随意顺序排序即可。
题目连接:https://leetcode.com/problems/custom-sort-string/
输入范围:
order
has length at most26
, and no character is repeated inorder
.str
has length at most200
.order
andstr
consist of lowercase letters only.
输入案例:
Example:
Input:
order = "cba"
str = "abcd"
Output: "cbad"
Explanation:
"a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
我的代码:
因为只需要 str 所有字符在 order 字符集内的,就要按照 order 排序,而其他的字符位置可以随意,那么我就直接用 hash 记录所有 str 字符数量,全部排序成 order 相对位置, 其他的字符集就重新拼进去就行。
Java:
class Solution {
public String customSortString(String order, String str) {
int[] mapStr = new int[26];
for(char ch : str.toCharArray()) mapStr[ch - 'a'] ++;
int index = 0;
StringBuilder builder = new StringBuilder();
for(char ch : order.toCharArray())
for(int i = ch - 'a'; mapStr[i] -- > 0;) builder.append(ch);
for(int i = 0;i < 26;i++)
while(mapStr[i] -- > 0) builder.append((char)(i + 'a'));
return builder.toString();
}
}
C++:
class Solution {
public:
string customSortString(string order, string str) {
int map[26] = {0};
for(int i = 0, len = str.length(); i < len; i ++) map[str[i] - 'a'] ++;
string res = "";
for(int i = 0, len = order.length(); i < len; i ++) {
char ch = order[i];
int index = ch - 'a';
while(map[index] -- > 0) res += ch;
}
for(int i = 0; i < 26; i ++)
while(map[i]-- > 0) res += (char)(i + 'a');
return res;
}
};