「这是我参与2022首次更文挑战的第22天,活动详情查看:2022首次更文挑战」
前言
每日一题,轻松解题
每日一题为刷题系列 每日刷一题LeetCode题,并且对题目进行分析,分享思路。
正文
:自定义字符串排序
难度:中等
题目要求:
给定两个字符串 order 和 s 。order 的所有单词都是 唯一 的,并且以前按照一些自定义的顺序排序。
对 s 的字符进行置换,使其与排序的 order 相匹配。更具体地说,如果在 order 中的字符 x 出现字符 y 之前,那么在排列后的字符串中, x 也应该出现在 y 之前。
返回 满足这个性质的 s 的任意排列 。
分析题目:
其实题目的要求就是,有两个字符串,a和b, a和b的字符排列顺序肯定不同,a不变现在改变b,把b中的字符顺序调换后,能与a字符串的顺序相匹配上,就说明成功。
举个例子
输入: order = "cba", s = "abcd"
输出: "cbad"
解释:
“a”、“b”、“c”是按顺序出现的,所以“a”、“b”、“c”的顺序应该是“c”、“b”、“a”。
因为“d”不是按顺序出现的,所以它可以在返回的字符串中的任何位置。“dcba”、“cdba”、“cbda”也是有效的输出。
:解题
方法一
理清思路:
首先找出在 T 中出现的所有的 S 的元素,并且将这些元素按照 S 中出现的相对顺序排序,然后把 T 中出现的但不在 S 中的元素添加到排好序的字符串中,就得到了我们想要的结果。
在将 T 中出现的但不在 S 中的元素添加到字符串时,无序关注顺序,因为这些元素并没有在 S 中出现,不需要满足排序关系。
编辑代码:
class Solution {
public String customSortString(String S, String T) {
// count[char] = the number of occurrences of 'char' in T.
// This is offset so that count[0] = occurrences of 'a', etc.
// 'count' represents the current state of characters
// (with multiplicity) we need to write to our answer.
int[] count = new int[26];
for (char c: T.toCharArray())
count[c - 'a']++;
// ans will be our final answer. We use StringBuilder to join
// the answer so that we more efficiently calculate a
// concatenation of strings.
StringBuilder ans = new StringBuilder();
// Write all characters that occur in S, in the order of S.
for (char c: S.toCharArray()) {
for (int i = 0; i < count[c - 'a']; ++i)
ans.append(c);
// Setting count[char] to zero to denote that we do
// not need to write 'char' into our answer anymore.
count[c - 'a'] = 0;
}
// Write all remaining characters that don't occur in S.
// That information is specified by 'count'.
for (char c = 'a'; c <= 'z'; ++c)
for (int i = 0; i < count[c - 'a']; ++i)
ans.append(c);
return ans.toString();
}
}
方法二
理清思路:
先转为数组,然后替换目标字符为数字,数字字符分两个数组,给数字的数组排序,然后把两个数组拼起来,把数字替换回目标字符
编辑代码:
var customSortString = function(order, s) {
s=s.split('')
var tmp=s
for(let i in order){
for(let j in s){
if(s[j]==order[i]){
s[j]=parseInt(i)
}
}
}
tmp=s.filter((value,index,array)=>{return ((typeof value )=='number')}).sort((a,b)=>a-b)
s=s.filter((value,index,array)=>{return ((typeof value )!='number')})
s=tmp.concat(s)
for(let i in order){
for(let j in s){
if(s[j]==i){
s[j]=order[i]
}
}
}
s=s.join('')
return s
};
总结
无论做什么分析最重要,其中我们分析了题目,分析了解题思路,其实在分析完解题思路后,代码其实就是很简单的事情了,养成习惯,无论做什么之前,都要进行分析,这样有助于你更快更好的完成这件事。