题解 | 字符串排序-golang最简洁最易懂解法

字符串排序

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
        a := scanner.Text()
		words := make([]word, 0)
		aa := []byte(a)
		for _, k := range aa {
			if k >= 'a' && k <= 'z' || k >= 'A' && k <= 'Z' {
                pos := 0
                if k>='a' {
                    //记录小写字母的相对位置
                    pos = int(k-'a')
                } else {
                    //记录大写字母的相对位置
                    pos = int(k-'A')
                }
               
				words = append(words, word{
					c:     k,
					pos: pos,
				})
			}
		}
		//稳定排序,相同元素排序前后相对位置不变
        sort.SliceStable(words, func(i, j int) bool {
            return words[i].pos < words[j].pos
        })
		for i, j := 0, 0; i < len(aa); i++ {
			if aa[i] >= 'a' && aa[i] <= 'z' || aa[i] >= 'A' && aa[i] <= 'Z' {
				aa[i] = words[j].c
				j++
			}
		}
		fmt.Println(string(aa))

	}
}

//记录每个字母和他的相对位置,忽略大小写
type word struct {
	c     byte
	pos int
}


#golang#
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务