Skip to content

Latest commit

 

History

History
63 lines (48 loc) · 1.06 KB

0151.md

File metadata and controls

63 lines (48 loc) · 1.06 KB

Reverse Words in a String

题目

Given an input string, reverse the string word by word.

 

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"
Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

思路

key: 遍历字符串清理空格

代码

func reverseWords(s string) string {
    strs := make([]string, 0)
    for i := 0; i < len(s); i++ {
        if s[i] == ' ' {
            continue
        }
        j := i
        for j = i; j < len(s); j++ {
            if s[j] == ' ' {
                break
            }
        }
        strs = append(strs, s[i:j])
        i = j
    }
    //fmt.Println(strs)
    res := ""
    for i := len(strs)-1; i > 0; i-- {
        res += strs[i] + " "
    }
    if len(strs) > 0 {
        res += strs[0]
    }
    return res
}