题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
package main import ( "fmt" "os" "sort" "strings" "bufio" ) // 插入排序 func insertSort(s string) string { size := len(s) // 先收集所有字符 var letters []byte for i:=0; i<size; i++ { if ('A' <= s[i] && s[i] <= 'Z') || ('a' <= s[i] && s[i] <= 'z') { letters = append(letters, s[i]) } } // 对所有字符忽略大小写稳定排序 sort.SliceStable(letters, func(i, j int) bool { return strings.ToLower(string(letters[i])) < strings.ToLower(string(letters[j])) }) sb := make([]byte, size) idx := 0 for i:=0; i<size; i++ { if ('A' <= s[i] && s[i] <= 'Z') || ('a' <= s[i] && s[i] <= 'z') { sb[i] = letters[idx] idx++ } else { sb[i] = s[i] } } return string(sb) } func main() { var s string inputReader := bufio.NewReader(os.Stdin) line, _, _ := inputReader.ReadLine() s = string(line) fmt.Println(insertSort(s)) }
// 本题输入一行字符串,所以采用 inputReader.ReadLine()