在Go (Golang)中颠倒给定句子中单词的方法

199 阅读1分钟

概述

目的是颠倒给定句子中的单词

例子

Input: "hello world"
Output: "word hello"

另一个例子。如果输入包含一个单词,那么该单词将被返回。

Input: "hello"
Output: "hello"

以下是我们的策略

  • 首先,我们反转整个字符串。因此,对于 "hello world",它变成了
"dlrow olleh"
  • 然后,我们反转每个词
"world hello"
  • 我们还需要照顾到结尾或开头的额外空格。

程序

以下是相同的程序。

package main

import (
	"fmt"
	"regexp"
	"strings"
)

func reverseWords(s string) string {

	runeArray := []rune(s)
	length := len(runeArray)

	reverseRuneArray := reverse(runeArray)

	for i := 0; i < length; {
		for i < length && string(reverseRuneArray[i]) == " " {
			i++
		}
		if i == length {
			break
		}
		wordStart := i

		for i < length && string(reverseRuneArray[i]) != " " {
			i++
		}

		wordEnd := i - 1

		reverseRuneArray = reverseIndex(reverseRuneArray, wordStart, wordEnd)

	}

	noSpaceString := strings.TrimSpace(string(reverseRuneArray))
	space := regexp.MustCompile(`\s+`)
	return space.ReplaceAllString(noSpaceString, " ")
}

func reverse(s []rune) []rune {
	length := len(s)
	start := 0
	end := length - 1
	for start < end {
		s[start], s[end] = s[end], s[start]
		start++
		end--
	}
	return s
}

func reverseIndex(s []rune, i, j int) []rune {

	start := i
	end := j
	for start < end {
		s[start], s[end] = s[end], s[start]
		start++
		end--
	}
	return s
}

func main() {
	output := reverseWords("hello world")
	fmt.Println(output)

	output = reverseWords("hello")
	fmt.Println(output)
}

输出

world hello
hello