说明

算法:Reverse Words in a String
LeetCode地址:https://leetcode.com/problems/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.

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) extra space.

解题思路1

翻转字符串里的单词, split() 先把单词拆解为wordsArray,倒序把word拼接即可。
时间复杂度为 O(N); 空间复杂度为O(N).

代码实现1

import java.util.Arrays;public class ReverseWordsInAString {public String reverseWords(String s) {s = s.trim();if (s.length() == 0) {return s;}String blankString = " ";String[] wordsArray = s.split(blankString);StringBuilder sb = new StringBuilder();for (int i = wordsArray.length - 1; i >= 0; i--) {String word =  wordsArray[i];word = word.trim();if (word.length() > 0) {sb.append(word).append(blankString);}}return sb.toString().trim();}public static void main(String[] args) {String input = "the sky is blue";ReverseWordsInAString obj = new ReverseWordsInAString();System.out.println("Input: \"" + input + "\"\n" + "Output: \"" + obj.reverseWords(input) + "\"") ;String input1 = "  hello world!  ";System.out.println("Input: \"" + input1 + "\"\n" + "Output: \"" + obj.reverseWords(input1) + "\"") ;String input2 = "a good   example";System.out.println("Input: \"" + input2 + "\"\n" + "Output: \"" + obj.reverseWords(input2) + "\"") ;}
}

运行结果1

Input: "the sky is blue"
Output: "blue is sky the"
Input: "  hello world!  "
Output: "world! hello"
Input: "a good   example"
Output: "example good a"

代码执行效率1

Runtime: 2 ms, faster than 92.72% of Java online submissions for Reverse Words in a String.
Memory Usage: 38.5 MB, less than 66.81% of Java online submissions for Reverse Words in a String.

解题思路2

降低空间复杂度,把字符串转为字符数组 > 字符数组原地翻转 > 找到单词在word内部翻转回来 > 清理多余的空字符并替换掉前面的字符 > 新建字符串,截取到前面有效字符。
时间复杂度为 O(N),空间复杂度也为O(N), 但是前面的系数明显会小于上面的。

代码实现2

import java.util.Arrays;public class ReverseWordsInAString {public String reverseWordsWithLessSpace(String s) {char[] chars = s.toCharArray();int len = chars.length;// step 1. reverse the whole stringsubReverse(chars, 0, len - 1);// step 2. reverse each wordsubReverseWords(chars, len);// step 3. clean up spacesreturn subCleanBlankChar(chars, len);}// trim leading, trailing and multiple spacespublic String subCleanBlankChar(char[] chars, int len) {int i = 0, j = 0;char blankChar = ' ';while (j < len) {// skip spaceswhile (j < len && chars[j] == blankChar) {j++;}// keep non spaceswhile (j < len && chars[j] != blankChar) {chars[i++] = chars[j++];}// skip spaceswhile (j < len && chars[j] == blankChar) {j++;}// keep only one spaceif (j < len) {chars[i++] = blankChar;}}return new String(chars).substring(0, i);}public void subReverseWords(char[] chars, int len) {char blankChar = ' ';int i = 0, j = 0;while (j < len) {// skip spaceswhile (j < len && chars[j] == blankChar) {j++;}i = j;// skip non spaceswhile (j < len && chars[j] != blankChar) {j++;}// reverse the wordsubReverse(chars, i, j - 1);}}// reverse a[] from a[i] to a[j]public void subReverse(char[] chars, int startIndex, int endIndex) {while (startIndex < endIndex) {char temp = chars[startIndex];chars[startIndex] = chars[endIndex];chars[endIndex] = temp;startIndex++;endIndex--;}}public static void main(String[] args) {String input = "the sky is blue";ReverseWordsInAString obj = new ReverseWordsInAString();System.out.println("Input: \"" + input + "\"\n" + "Output: \"" + obj.reverseWordsWithLessSpace(input) + "\"") ;String input1 = "  hello world!  ";System.out.println("Input: \"" + input1 + "\"\n" + "Output: \"" + obj.reverseWordsWithLessSpace(input1) + "\"") ;String input2 = "a good   example";System.out.println("Input: \"" + input2 + "\"\n" + "Output: \"" + obj.reverseWordsWithLessSpace(input2) + "\"") ;}
}

运行结果2

Input: "the sky is blue"
Output: "blue is sky the"
Input: "  hello world!  "
Output: "world! hello"
Input: "a good   example"
Output: "example good a"

代码执行效率2

Runtime: 4 ms, faster than 71.55% of Java online submissions for Reverse Words in a String.
Memory Usage: 37.7 MB, less than 83.83% of Java online submissions for Reverse Words in a String.

总结

翻转字符串里的单词,第一种方案:拆分单词数组,倒序拼接最直接,也是最快的。第二种方案:减少空间复杂度,用到字符数组原地排序的技巧。

代码下载:
https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/popular/ReverseWordsInAString.java

算法:Reverse Words in a String(翻转字符串里的单词)相关推荐

  1. 代码随想录算法训练营第八天|● 344.反转字符串● 541. 反转字符串II● 剑指Offer 05.替换空格● 151.翻转字符串里的单词● 剑指Offer58-II.左旋转字符

    一.344.反转字符串 力扣 思路:很简单的一个for循环双指针,left和right交换. class Solution {public void reverseString(char[] s) { ...

  2. 代码随想录算法训练营第八天|344.反转字符串 541. 反转字符串II 剑指Offer 05.替换空格 151.翻转字符串里的单词 剑指Offer58-II.左旋转字符串

    一.344.反转字符串 题目:编写一个函数,其作用是将输入的字符串反转过来.输入字符串以字符数组 char[] 的形式给出. 不要给另外的数组分配额外的空间,你必须原地修改输入数组.使用 O(1) 的 ...

  3. 数组翻转_LeetCode刷题实战151:翻转字符串里的单词

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !今天和大家聊 ...

  4. 72.编辑距离105.前序中序遍历序列构造二叉树151.翻转字符串里的单词104.二叉树的最大深度76.最小覆盖子串110.平衡二叉树31.下一个排列

    72.编辑距离 给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数 .你可以对一个单词进行如下三种操作:插入一个字符,删除一个字符,替换一个字符. ...

  5. Lc151翻转字符串里的单词

    翻转字符串里的单词 差一点就做出来,一开始用空格拆分单词,但是这个样例the sky is blue 没有通过,单词之间有多个空格的情况,然后看了评论区--学了一个正则表达式 /\s+/这是正则表达式 ...

  6. python单词反转_翻转字符串里的单词

    翻转字符串里的单词 题目要求 给定一个字符串,逐个翻转字符串中的每个单 示例: 输入: " the sky is blue", 输出: "blue is sky the ...

  7. [leetcode]151.翻转字符串里的单词

    给你一个字符串 s ,逐个翻转字符串中的所有 单词 . 单词 是由非空格字符组成的字符串.s 中使用至少一个空格将字符串中的 单词 分隔开. 请你返回一个翻转 s 中单词顺序并用单个空格相连的字符串. ...

  8. LeetCode--151. 翻转字符串里的单词(字符串翻转,字符串分割)

    翻转字符串里的单词(双指针,字符串分割) 1. 题目描述 2. 题目分析 3. C语言实现 4. Python实现 1. 题目描述 难度:中等 2. 题目分析 这道题我们需要注意的点有以下几个: 每个 ...

  9. 算法--------翻转字符串里的单词(Java版本)

    题目: 给定一个字符串,逐个翻转字符串中的每个单词.示例 1:输入: "the sky is blue" 输出: "blue is sky the" 示例 2: ...

  10. 代码随想录算法训练营第08天 | LeetCode 344.反转字符串,541. 反转字符串2,剑指Offer 05.替换空格,151.翻转字符串里的单词,剑指Offer58-II.左旋转字符串

    LeetCode [344. 反转字符串] 题目:编写一个函数,其作用是将输入的字符串反转过来.输入字符串以字符数组 s 的形式给出. 不要给另外的数组分配额外的空间,你必须**原地修改输入数组**. ...

最新文章

  1. leetcood学习笔记-45-跳跃游戏二
  2. Sql server 获得某一部门下的所有子部门。根据子部门获得它的上级部门。
  3. C++ for循环跳过某一项求和
  4. SAP PP模块调研问卷
  5. html导航去下划线,纯CSS实现导航栏下划线跟随的示例代码
  6. sqlcipher java_纯java环境下sqlsqlcipher解密sqlite数据库文件
  7. jboss项目导入idea_JBoss BPM Suite快速指南–将外部数据模型导入BPM项目
  8. 企业级实战02_SpringMVC整合ActiveMQ 实战需求
  9. 如何在面试时搞定 Java 虚拟机?
  10. CentOS7与CentOS6区别及特点
  11. Java:for循环出现for(int i : arr)
  12. pe系统怎么安装linux系统教程,U盘安装windows+ubuntu+winpe三系统详细教程
  13. garbor 特征 matlab,Gabor小波滤波用于纹理特征提取
  14. mysqloffset什么意思_MySQL中OFFSET和FETCH的详解
  15. php怎么使用sendcloud,高级功能 - SendCloud 文档中心 - SendCloud 文档中心
  16. 【论文阅读】Locally Adaptive Color Correction for Underwater Image Dehazing and Matching
  17. 消防管道标志色号_消防标志的起步问题
  18. Qt生成exe错误:无法定位程序输入点_cxa_throw_bad_array_new_length于动态链接库最终解决方法
  19. 推箱子游戏java毕业答辩ppt_基于Java推箱子游戏的设计与实现
  20. [vim] 滚动屏幕快捷键记忆

热门文章

  1. dbeaver 修改数据_GitHub 上 5 款超好用的数据库 GUI 带你玩转 MongoDB、Redis、SQL 数据库...
  2. r语言 rgl 强制过程中_R语言中的方差分析方法汇总
  3. iOS开发UI篇--仿射变换(CGAffineTransform)使用小结
  4. Windows 7 “Tunnel adapter Local Area Connection” 现象(IPv6)
  5. 00-JavaScript基础-基本概念
  6. Saltstack系列2:Saltstack远程执行命令
  7. 数据结构 《18》----RMQ 与 LCA 的等价性 (一)
  8. ERP选型需把握主动权!
  9. js实现登录表单验证
  10. CodeBlocks中文乱码