题解 | #句子逆序#
句子逆序
https://www.nowcoder.com/practice/48b3cb4e3c694d9da5526e6255bb73c3
package main import ( "fmt" "os" "bufio" ) func reverse(sb []byte, left int, right int) { // 对 sb[left, right] 区间进行反转,左闭右闭区间 for i,j := left,right; i<j; i,j = i+1,j-1 { sb[i], sb[j] = sb[j], sb[i] } } func generateReverseSentence(s string) string { sb := []byte(s) size := len(sb) // 整体反转 reverse(sb, 0, size-1) // 对每个单词进行反转 slow, fast := 0, 0 for fast < size { for fast < size && sb[fast] != ' ' { fast++ } reverse(sb, slow, fast-1) slow = fast + 1 fast = slow } return string(sb) } func main() { var s string inputReader := bufio.NewReader(os.Stdin) data, _, _ := inputReader.ReadLine() s = string(data) fmt.Println(generateReverseSentence(s)) }
// 本题为输入一个字符串,所以采用标准处理:inputReader.ReadLine()