leetcode update

This commit is contained in:
gameloader 2024-03-11 19:08:50 +08:00
parent f159fc76cd
commit 6d044ea166

View File

@ -877,3 +877,52 @@ func intersection(nums1 []int, nums2 []int) []int {
return res
}
```
## day14 2024-03-11
### 791. Custom Sort String
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.
![0311fLXVhVrYfXgA](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/0311fLXVhVrYfXgA.png)
### 题解
本题初始想先扫描s字符串, 使用一个map记录字符串中各个字符的数量, 再遍历order依次将字符按数量附加到末尾即可. 但考虑到字符只有26个小写英文字母, 使用一个长度为26的数组来保存对应位置的英文字母的数量. 再遍历要比map速度快.
### 代码
```go
func customSortString(order string, s string) string {
a := 'a'
result := ""
numbers := make([]int, 26)
for _, character := range s{
numbers[character-a]++
}
for _,c := range order{
temp := numbers[c-a]
for i:=0;i<temp;i++{
numbers[c-a]--
result += string(c)
}
}
for key,c := range numbers{
if c!=0{
for i:=0;i<c;i++{
result += string(rune(int(a)+key))
}
}
}
return result
}
```
### 总结
注意题中条件, 遍历的类型有限的情况下直接使用数组保存, 遍历起来速度要快得多.