题解 | 字符串排序

字符串排序

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

package main

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


func getInputTxt() []byte {
    var str []byte
    reader := bufio.NewReader(os.Stdin)
    inputText, _ := reader.ReadString('\n')
    str = []byte(strings.TrimSuffix(inputText, "\n"))
    return str
}

func checkChar(b byte) bool {
    if (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') {
        return true
    } else {
        return false
    }
}

func compare(a, b byte) bool{
    aTemp := strings.ToUpper(string(a))
    bTemp := strings.ToUpper(string(b))
    if aTemp[0] > bTemp[0] {
        return true
    } else {
        return false
    }
}

func main() {
    str := getInputTxt()
    strLen := len(str)
    for i:= 0; i < strLen - 1; i++ {
        maxIndex := 0 // 只比较相邻的两个字符,谁大谁靠后。内层循环其实跟i没关系,只是作为计数
        // str[i]是字母
        for j:= 0; j < strLen - i; j++ {
            if checkChar(str[j]) {
                // str[j]也是字母
                if (compare(str[maxIndex], str[j])) {
                    str[maxIndex], str[j] = str[j], str[maxIndex]
                }
                maxIndex = j
            }
        }
    }
    fmt.Println(string(str))
}

全部评论

相关推荐

牛至超人:我将凌晨两点给你打电话
点赞 评论 收藏
分享
粉红恶魔派星星:炸了,偶遇kpi面。面试官一直在忙自己的事情。1.手写责任链 2.手写快排 3.linux定时任务的命令 4.springboot的定时任务 5.问了一条实习
今天你投了哪些公司?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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