[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 }
相关文章
相关标签/搜索