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

    Solution:

    class Solution {
    public:
        void reverseWords(string &s) {
            int len = s.length(), start = 0, curLen = 0;
            
            string ans = "", tmp = "";
            bool isWord = false, notStartEmpty = false;
            for(int i = len - 1;i >= 0;i--)
            {
                if(s[i] == ' ')
                {
                    if(isWord)
                    {
                        isWord = false;
                        ans += s.substr(start - curLen + 1, curLen);
                        curLen = 0;
                    }
                    if(notStartEmpty)
                        tmp += s[i];
                }
                else
                {
                    if(isWord)
                    {
                        curLen++;
                    }
                    else
                    {
                        isWord = true;
                        notStartEmpty = true;
                        if(tmp.length() > 0)
                         {
                            ans += " ";
                            tmp = "";
                        }
                        start = i;
                        curLen = 1;
                    }
                }
            }
            if(curLen != 0)
                ans += s.substr(start - curLen + 1, curLen);
            s = ans;
        }
    };
  • 相关阅读:
    【洛谷P2660烤鸡】
    cogs448
    排队打水
    洛谷U36590搬书
    NOIP2012借教室
    归并排序模版
    NOIP2015神奇的幻方
    NOIP2006能量项链
    NOIP2003加分二叉树
    NOI1995石子合并&多种石子合并
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3597349.html
Copyright © 2011-2022 走看看