[Swift]LeetCode151. 翻轉字符串裏的單詞 | Reverse Words in a String

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-wpzvsqqn-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

Example:  github

Input: "",
Output: "".
the sky is blueblue is sky the

Note:微信

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.spa


給定一個字符串,逐個翻轉字符串中的每一個單詞。code

示例:  htm

輸入: "",
輸出: "".
the sky is blueblue is sky the

說明:blog

  • 無空格字符構成一個單詞。
  • 輸入字符串能夠在前面或者後面包含多餘的空格,可是反轉後的字符不能包括。
  • 若是兩個單詞間有多餘的空格,將反轉後單詞間的空格減小到只含一個。

進階: 請選用C語言的用戶嘗試使用 O(1) 空間複雜度的原地解法。ip


1 class class Solution {
2     func reverseWords(_ s: String) -> String {
3           return String(s.split(separator: " ").reversed().reduce("") { total, word in total + word + " "}.dropLast())
4     }
5 }
相關文章
相關標籤/搜索