返回介绍

solution / 0700-0799 / 0791.Custom Sort String / README_EN

发布于 2024-06-17 01:03:34 字数 9374 浏览 0 评论 0 收藏 0

791. Custom Sort String

中文文档

Description

You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.

Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.

Return _any permutation of _s_ that satisfies this property_.

 

Example 1:

Input: order = "cba", s = "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.

Example 2:

Input: order = "bcafg", s = "abcd"

Output: "bcad"

Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.

Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order.

 

Constraints:

  • 1 <= order.length <= 26
  • 1 <= s.length <= 200
  • order and s consist of lowercase English letters.
  • All the characters of order are unique.

Solutions

Solution 1

class Solution:
  def customSortString(self, order: str, s: str) -> str:
    d = {c: i for i, c in enumerate(order)}
    return ''.join(sorted(s, key=lambda x: d.get(x, 0)))
class Solution {
  public String customSortString(String order, String s) {
    int[] d = new int[26];
    for (int i = 0; i < order.length(); ++i) {
      d[order.charAt(i) - 'a'] = i;
    }
    List<Character> cs = new ArrayList<>();
    for (int i = 0; i < s.length(); ++i) {
      cs.add(s.charAt(i));
    }
    cs.sort((a, b) -> d[a - 'a'] - d[b - 'a']);
    return cs.stream().map(String::valueOf).collect(Collectors.joining());
  }
}
class Solution {
public:
  string customSortString(string order, string s) {
    int d[26] = {0};
    for (int i = 0; i < order.size(); ++i) d[order[i] - 'a'] = i;
    sort(s.begin(), s.end(), [&](auto a, auto b) { return d[a - 'a'] < d[b - 'a']; });
    return s;
  }
};
func customSortString(order string, s string) string {
  d := [26]int{}
  for i := range order {
    d[order[i]-'a'] = i
  }
  cs := []byte(s)
  sort.Slice(cs, func(i, j int) bool { return d[cs[i]-'a'] < d[cs[j]-'a'] })
  return string(cs)
}
function customSortString(order: string, s: string): string {
  const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0);
  const n = order.length;
  const d = new Array(26).fill(n);
  for (let i = 0; i < n; i++) {
    d[toIndex(order[i])] = i;
  }
  return [...s].sort((a, b) => d[toIndex(a)] - d[toIndex(b)]).join('');
}
impl Solution {
  pub fn custom_sort_string(order: String, s: String) -> String {
    let n = order.len();
    let mut d = [n; 26];
    for (i, c) in order.as_bytes().iter().enumerate() {
      d[(c - b'a') as usize] = i;
    }
    let mut ans = s.chars().collect::<Vec<_>>();
    ans.sort_by(|&a, &b|
      d[((a as u8) - ('a' as u8)) as usize].cmp(&d[((b as u8) - ('a' as u8)) as usize])
    );
    ans.into_iter().collect()
  }
}

Solution 2

class Solution:
  def customSortString(self, order: str, s: str) -> str:
    cnt = Counter(s)
    ans = []
    for c in order:
      ans.append(c * cnt[c])
      cnt[c] = 0
    for c, v in cnt.items():
      ans.append(c * v)
    return ''.join(ans)
class Solution {
  public String customSortString(String order, String s) {
    int[] cnt = new int[26];
    for (int i = 0; i < s.length(); ++i) {
      ++cnt[s.charAt(i) - 'a'];
    }
    StringBuilder ans = new StringBuilder();
    for (int i = 0; i < order.length(); ++i) {
      char c = order.charAt(i);
      while (cnt[c - 'a']-- > 0) {
        ans.append(c);
      }
    }
    for (int i = 0; i < 26; ++i) {
      while (cnt[i]-- > 0) {
        ans.append((char) ('a' + i));
      }
    }
    return ans.toString();
  }
}
class Solution {
public:
  string customSortString(string order, string s) {
    int cnt[26] = {0};
    for (char& c : s) ++cnt[c - 'a'];
    string ans;
    for (char& c : order)
      while (cnt[c - 'a']-- > 0) ans += c;
    for (int i = 0; i < 26; ++i)
      if (cnt[i] > 0) ans += string(cnt[i], i + 'a');
    return ans;
  }
};
func customSortString(order string, s string) string {
  cnt := [26]int{}
  for _, c := range s {
    cnt[c-'a']++
  }
  ans := []rune{}
  for _, c := range order {
    for cnt[c-'a'] > 0 {
      ans = append(ans, c)
      cnt[c-'a']--
    }
  }
  for i, v := range cnt {
    for j := 0; j < v; j++ {
      ans = append(ans, rune('a'+i))
    }
  }
  return string(ans)
}
function customSortString(order: string, s: string): string {
  const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0);
  const count = new Array(26).fill(0);
  for (const c of s) {
    count[toIndex(c)]++;
  }
  const ans: string[] = [];
  for (const c of order) {
    const i = toIndex(c);
    ans.push(c.repeat(count[i]));
    count[i] = 0;
  }
  for (let i = 0; i < 26; i++) {
    if (!count[i]) continue;
    ans.push(String.fromCharCode('a'.charCodeAt(0) + i).repeat(count[i]));
  }
  return ans.join('');
}
impl Solution {
  pub fn custom_sort_string(order: String, s: String) -> String {
    let mut count = [0; 26];
    for c in s.as_bytes() {
      count[(c - b'a') as usize] += 1;
    }
    let mut ans = String::new();
    for c in order.as_bytes() {
      for _ in 0..count[(c - b'a') as usize] {
        ans.push(char::from(*c));
      }
      count[(c - b'a') as usize] = 0;
    }
    for i in 0..count.len() {
      for _ in 0..count[i] {
        ans.push(char::from(b'a' + (i as u8)));
      }
    }
    ans
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文