leetcode186. 翻转字符串里的单词 II

举报
兔老大 发表于 2021/04/23 00:51:47 2021/04/23
【摘要】 给定一个字符串,逐个翻转字符串中的每个单词。 示例: 输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] 输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] 注意: 单词的定义是不包含空格的一系列字符 输入字符串...

给定一个字符串,逐个翻转字符串中的每个单词。

示例:

输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
注意:

单词的定义是不包含空格的一系列字符
输入字符串中不会包含前置或尾随的空格
单词与单词之间永远是以单个空格隔开的
进阶:使用 O(1) 额外空间复杂度的原地解法。

思路:先反转每个单词,然后总体再翻转。


  
  1. class Solution {
  2. public void reverseWords(char[] s) {
  3. int start=0;
  4. for(int i=0;i<s.length;i++){
  5. if(s[i]==' '){
  6. reverseWord(s,start,i-1);
  7. start=i+1;
  8. }
  9. }
  10. reverseWord(s,start,s.length-1);
  11. reverseWord(s,0,s.length-1);
  12. }
  13. public void reverseWord(char[] s,int start,int end){
  14. char temp;
  15. while(start<end){
  16. temp=s[start];
  17. s[start]=s[end];
  18. s[end]=temp;
  19. start++;
  20. end--;
  21. }
  22. }
  23. }

文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。

原文链接:fantianzuo.blog.csdn.net/article/details/104100599

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。