[Leetcode学习-java&c++]Custom Sort String

46 篇文章 0 订阅

问题:

难度:medium

说明:

给出两个字符串,要求将str 字符串按照 order 的相对顺序进行排序,所有的输入字符都是 [a-z]* ,然后不在 order 字符集的 str 字符就按照随意顺序排序即可。

题目连接:https://leetcode.com/problems/custom-sort-string/

输入范围:

  • order has length at most 26, and no character is repeated in order.
  • str has length at most 200.
  • order and str 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;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值