题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
package main import ( "fmt" "strings" "bufio" "os" ) func isLetter(ch byte) bool { return ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z') } func reverseWords(s string) string { size := len(s) s = strings.Trim(s, " ") slow, fast := 0, 0 var words []string for fast < size { if !isLetter(s[fast]) { words = append(words, s[slow:fast]) for !isLetter(s[fast]) && fast<size {fast++} slow = fast } else { fast++ } } if fast == size && isLetter(s[fast-1]) { words = append(words, s[slow:fast]) } for i,j:=0,len(words)-1; i<j; i,j=i+1,j-1 { words[i], words[j] = words[j], words[i] } return strings.Join(words, " ") } func main() { var s string inputReader := bufio.NewReader(os.Stdin) line, _, _ := inputReader.ReadLine() s = string(line) fmt.Println(reverseWords(s)) }
// 本题输入为一行带空格的字符串,所以采用 inputReader.ReadLine()