zoukankan      html  css  js  c++  java
  • leetcode[151]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".

    click to show clarification.

    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) {
        if(s.empty())return;
        string tmp="";
        string str="";
        int i=0;
        while(i<s.length())
        {
            while(s[i]==' '&&i<s.length())i++;
            if(s[i]!=' '&&i<s.length())
            {
                while(s[i]!=' '&&i<s.length())tmp=s[i++]+tmp;
                str+=(tmp+' ');
                tmp="";
            }
        }
        reverse(str.begin(),str.end());
        int n=str[0]==' '?1:0;
        s=str.substr(n,str.size());
        return;
    }
    };
  • 相关阅读:
    08-01集合运算
    07-03成员运算符
    07-02集合
    07-01结构与封装
    06-01字符串格式化.md
    06-03线性结构与切片
    06-02字符串与bytes
    05-02命名元组
    05-01元组
    04-01列表与常用操作
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4280723.html
Copyright © 2011-2022 走看看