题解 | 字符串排序

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	var input0 string

	input := bufio.NewScanner(os.Stdin)
	input.Scan()
	input0 = input.Text()

	bytes0 := []byte{}
	inputBytes := []byte(input0)
	for _, b := range inputBytes {
		switch {
		case (b >= 'a' && b <= 'z'), (b >= 'A' && b <= 'Z'):
			bytes0 = append(bytes0, b)
		}
	}

	// fmt.Printf("bytes0: %#v\n", string(bytes0))
	sortedBytes0 := customSort(string(bytes0))
	// fmt.Printf("sortedBytes0: %#v\n", sortedBytes0)

	positionIdx := 0
	for inputIdx, b := range inputBytes {
		switch {
		case (b >= 'a' && b <= 'z'), (b >= 'A' && b <= 'Z'):
			inputBytes[inputIdx] = sortedBytes0[positionIdx]
			positionIdx++
		}
	}

	fmt.Println(string(inputBytes))
}

func customSort(str string) string {
	l := len(str)

	lowerStrBytes := []byte(strings.ToLower(str))
	rawBytes := []byte(str)
	for i := 1; i <= l; i++ {
		for j := 0; j < l-1; j++ {
			if lowerStrBytes[j] > lowerStrBytes[j+1] {
				tmp := rawBytes[j]
				rawBytes[j] = rawBytes[j+1]
				rawBytes[j+1] = tmp
				lowerStrBytes = []byte(strings.ToLower(string(rawBytes)))
			}
		}
	}

	// fmt.Printf("str: %v\n", string(str))
	// fmt.Printf("customSort: %v\n", string(rawBytes))
	return string(rawBytes)
}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务