Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created March 28, 2020 15:45
Show Gist options
  • Select an option

  • Save alldroll/10789ea8fc8ee857807b7b674836c8b0 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/10789ea8fc8ee857807b7b674836c8b0 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/reverse-words-in-a-string
func reverseWords(s string) string {
words := ""
chars := []rune(s)
anchor := 0
for i := 0; i < len(chars); i++ {
if chars[i] == rune(' ') {
if anchor < i {
if len(words) > 0 {
words = string(chars[anchor: i + 1]) + words
} else {
words = string(chars[anchor: i])
}
}
anchor = i + 1
}
}
if anchor < len(chars) {
if len(words) > 0 {
words = string(chars[anchor: len(chars)]) + " " + words
} else {
words = string(chars[anchor: len(chars)])
}
}
return words
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment