题解 | #句子逆序#

句子逆序

https://www.nowcoder.com/practice/48b3cb4e3c694d9da5526e6255bb73c3

package main

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

func reverseSentence(sentence string) string {
    words := strings.Split(sentence, " ")
    reversedWords := make([]string, len(words))

    for i := 0; i < len(words); i++ {
        reversedWords[len(words)-i-1] = words[i]
    }

    return strings.Join(reversedWords, " ")
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)

    for scanner.Scan() {
        sentence := scanner.Text()
        reversedSentence := reverseSentence(sentence)
        fmt.Println(reversedSentence)
    }
}

这段代码首先定义了一个reverseWords函数,用于将输入的句子按单词逆序排列。它通过使用strings.Split函数将句子拆分成单词,并使用一个循环将单词逆序存储在reversedWords切片中。最后,使用strings.Join函数将逆序排列的单词重新组合成句子。

main函数中,我们使用bufio.Scanner从标准输入读取多行输入。对于每一行输入,调用reverseWords函数得到逆序排列的句子,并使用fmt.Println打印结果。

请注意,此代码假设输入的每行只包含一个句子,并且句子中的单词由空格分隔。

错误示例:

package main

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

func reverseSentence(sentence string) string {
    words := strings.Split(sentence, " ")
    reversedWords := make([]string, len(words))

    for i := len(words) - 1; i >= 0; i-- {
        reversedWords = append(reversedWords, words[i])
    }

    return strings.Join(reversedWords, " ")
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)

    for scanner.Scan() {
        sentence := scanner.Text()
        reversedSentence := reverseSentence(sentence)
        fmt.Println(reversedSentence)
    }
}

PS D:\Workspace\Go\src\projects\demo> go run main.go

I am a boy

boy a am I

全部评论

相关推荐

鬼迹人途:你去投一投尚游游戏,服务器一面,第一个图算法,做完了给你一个策略题,你给出方案他就提出低概率问题,答不上当场给你挂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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