73th LeetCode Weekly Contest Custom Sort String

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

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

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

Example :
Input: 
S = "cba"
T = "abcd"
Output: "cbad"
Explanation: 
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". 
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.

 

Note:

  • S has length at most 26, and no character is repeated in S.
  • T has length at most 200.
  • S and T consist of lowercase letters only.

S是一种字母的排序方式,现在让T按照S的排序方式再输出一次,在S没有出现的字母就随便排,S不会出现相同字母

首先T和S都出现的字母,我们按照S的字母出现位置放进新的字符串里,然后呢,没出现的放最后,再然后就是把空的位置去掉就好了。

复制代码
 1 class Solution {
 2 public:
 3     map<char,int>Mp,mp;
 4     string customSortString(string S, string T) {
 5        string Str="";
 6        string Ctr="";
 7        int lens=S.length();
 8        int lent=T.length();
 9        for(int i=0;i<max(lent,lens);i++){
10             Str+='#';
11        }
12        for(int i=0;i<lens;i++){
13             Mp[S[i]]=i+1;
14        }
15        for(int i=0;i<lent;i++){
16            mp[T[i]]++;
17         if(Mp[T[i]]==0){
18            continue;
19         }else{
20             Str[Mp[T[i]]-1]=T[i];
21         }
22        }
23         //cout<<Str<<endl;
24        for(int i=0;i<max(lent,lens);i++){
25             for(int j=0;j<mp[Str[i]];j++){
26                     Ctr+=Str[i];
27                 }
28        }
29        for(int i=0;i<lent;i++){
30             if(Mp[T[i]]==0){
31                 Ctr+=T[i];
32             }
33        }
34        return Ctr;
35     }
36 };
复制代码

 

posted @   樱花落舞  阅读(236)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示