题解 | #删除字符串中出现次数最少的字符#
删除字符串中出现次数最少的字符
https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9
package main
import (
"fmt"
"sort"
"bufio"
"os"
)
type ByteCnt struct {
Ch byte
Cnt int
}
func removeMinDupElement(s string) string {
size := len(s)
m := make(map[byte]int, 0)
for i:=0; i<size; i++ {
m[s[i]]++
}
var byteCntList []ByteCnt
for k := range m {
byteCntList = append(byteCntList, ByteCnt{k, m[k]})
}
// 按照频次从低到高排序
sort.Slice(byteCntList, func(i, j int) bool {
return byteCntList[i].Cnt < byteCntList[j].Cnt
})
// 如果只有一个元素,则返回空
if len(byteCntList) == 1 {
return ""
}
toBeDeleteByte := make(map[byte]struct{}, 0)
for idx:=0; idx<len(byteCntList); idx++ {
if idx > 0 && byteCntList[idx].Cnt != byteCntList[idx-1].Cnt {
break
}
toBeDeleteByte[byteCntList[idx].Ch] = struct{}{}
}
var slow int
sb := make([]byte, size)
for fast:=0; fast<size;fast++ {
if _, ok := toBeDeleteByte[s[fast]]; !ok {
sb[slow] = s[fast]
slow++
}
}
return string(sb[:slow])
}
func main() {
var s string
inputReader := bufio.NewReader(os.Stdin)
line, _, _ := inputReader.ReadLine()
s = string(line)
fmt.Println(removeMinDupElement(s))
}
// 本题输入一个字符串,故采用:inputReader.ReadLine()
CVTE公司福利 672人发布
查看8道真题和解析