博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-151-Reverse Words in s String
阅读量:7112 次
发布时间:2019-06-28

本文共 1086 字,大约阅读时间需要 3 分钟。

算法描述:

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

Example:  

Input: "the sky is blue",Output: "blue 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.

解题思路:先逐词翻转,再整句翻转。注意去除空格。

void reverseWords(string &s, int i, int j){    while(i < j){        char temp = s[i];        s[i++]=s[j];        s[j--]=temp;            }   }void reverseWords(string &s){    int i = 0;    int j = 0;    int l = 0;    int n = s.size();    int count = 0;    while(true){        while(i < n && s[i] == ' ') i++;        if(i==n) break;        if(count) s[j++] = ' ';        l=j;        while(i < n && s[i]!= ' ') {s[j]=s[i]; j++; i++;}        reverseWords(s,l,j-1);        count++;    }    s.resize(j);    reverseWords(s,0,j-1);}

 

转载于:https://www.cnblogs.com/nobodywang/p/10354474.html

你可能感兴趣的文章
PHP+tcpdf的生成
查看>>
linux设置iptables防火墙的详细步骤(centos防火墙设置方法)
查看>>
二十六个月Android学习工作总结【转】
查看>>
Lua屏蔽对象方法和恢复的方法
查看>>
支持向量回归
查看>>
父级元素点击,遮盖了子元素的点击
查看>>
Unity ShaderLab学习总结
查看>>
CoordinatorLayout与滚动的处理
查看>>
Asteroids
查看>>
Eclipse中使用github
查看>>
解决LoggerFactory is not a Logback LoggerContext but Logback is on the classpath
查看>>
微软改名部又出动啦!微软宣布VSTS改名为Azure DevOps
查看>>
亲爱的老板:程序员的10分钟就是3个小时
查看>>
SQL Server 通过备份文件初始化复制
查看>>
Motion JPEG in Flash and Java
查看>>
Linq的分组功能
查看>>
使用 Jackson 树连接线形状
查看>>
学习mysql代码的方法和目标
查看>>
【读后感】暗时间
查看>>
终于找到IE10 Browser Mode为IE10 compat View的真相
查看>>