• 791. Custom Sort String


    order and str are strings composed of lowercase letters. In order, no letter occurs more than once.

    order was sorted in some custom order previously. We want to permute the characters of str so that they match the order that order was sorted. More specifically, if x occurs before y in order, then x should occur before y in the returned string.

    Return any permutation of str (as a string) that satisfies this property.

    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.
    

    Note:

    • 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.
    class Solution {
        public String customSortString(String order, String str) {
            int[] arr = new int[26];
            for(char c: str.toCharArray()) arr[c - 'a']++;
            StringBuilder sb = new StringBuilder();
            for(char c : order.toCharArray()) {
                int f = arr[c - 'a'];
                while(f > 0) {
                    sb.append(c);
                    arr[c - 'a']--;
                    f--;
                }
            }
            for(int i = 0; i < 26; i++) {
                int f = arr[i];
                while(f > 0) {
                    sb.append((char)('a' + i));
                    f--;
                }
            }
            return sb.toString();
        }
    }

    frequency

  • 相关阅读:
    PUTTY与SecureCRT的比较
    java中volatile关键字的含义
    java中引用的原理
    Java陷阱之assert关键字
    脏读 幻读 不可重复读
    JAVA 的wait(), notify()与synchronized同步机制
    线程状态转换图
    并行、并发、同步和互斥
    B-树学习笔记
    平衡二叉树及其应用场景
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/15013571.html
Copyright © 2020-2023  润新知