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

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

Reverse Words in a String

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

For example,

Given s = "the sky is blue",
return "blue is sky the".

Clarification:

 

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
 
一次遍历,将所有遇到的单词加在头部。
class Solution {public:    void reverseWords(string &s)     {        string rs = "";        int i = 0;        while(true)        {            // skip leading space            while(i < s.size() && s[i] == ' ')                i ++;            string word = "";            // s[i] points to first non-space            while(i < s.size() && s[i] != ' ')            {                word += s[i];                i ++;            }            if(word != "")                rs = word + " " + rs;            else    // i == s.size()                break;        }        if(rs != "")            rs.erase(rs.end()-1);   // if rs contains words, erase the last space        s = rs;    }};

转载地址:http://nsvbx.baihongyu.com/

你可能感兴趣的文章
TortoiseSVN中图标的含义
查看>>
VC中实现文字竖排的简单方法
查看>>
深入理解浏览器的缓存机制
查看>>
又拍云沈志华:如何打造一款安全的App
查看>>
dubbo源码分析-架构
查看>>
Windows phone 8 学习笔记
查看>>
我的友情链接
查看>>
LeetCode--112--路径总和
查看>>
感悟贴2016-05-13
查看>>
DEV-C++ 调试方法简明图文教程(转)
查看>>
参加婚礼
查看>>
Java重写equals方法和hashCode方法
查看>>
Spark API编程动手实战-07-join操作深入实战
查看>>
Spring ’14 Wave Update: Installing Dynamics CRM on Tablets for Windows 8.1
查看>>
MySQL 备份与恢复
查看>>
TEST
查看>>
PAT A1037
查看>>
(六)Oracle学习笔记—— 约束
查看>>
[Oracle]如何在Oracle中设置Event
查看>>
top.location.href和localtion.href有什么不同
查看>>