zoukankan      html  css  js  c++  java
  • Reverse Words in a String

    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.

    Answer:

    void re(int start, int end, string &s)
    {
        int n = end - start + 1;
        for (int i = start; i < start + n / 2; i++)
        {
            char c = s[i];
            s[i] = s[end - i + start];
            s[end - i + start] = c;
        }
    }
    
    void reverseWords(string &s)
    {
        int n = s.length();
        int flag = 1;
        int start = 0;
        int end = 0;
    
        re(0, n - 1, s);
    
        if (n == 1)
        {
            if (s[0] == ' ')
            {
                s = s.substr(0, 0);
            }
        }
        else
        {
            for (int i = 0; i < n; i++)
            {
                if (s[i] == ' ')
                {
                    if (flag == 0)
                    {
                        re(start, end - 1, s);
                        s[end] = ' ';
                        start = ++end;
                    }
                    flag = 1;
                }
                else
                {
                    s[end++] = s[i];
                    flag = 0;
                }
            }
            if (start != end)
            {
                re(start, end - 1, s);
            }
            s = s.substr(0, end);
            if (s[end - 1] == ' ')
            {
                s = s.substr(0, end - 1);
            }
        }
    }
  • 相关阅读:
    如何写README.md
    (2020-03-29)--------paper list
    ROS(八)----示例
    ROS(七)----动态参数
    ROS(六)----参数
    ROS(四)---自定义消息.msg
    ROS(三)-----节点的定义
    ROS(二)-------RoboWare Studio
    ROS(一)-----ros 安装
    pytorch(4)----nn.Module、nn.functional、nn.Sequential、nn.optim
  • 原文地址:https://www.cnblogs.com/ich1990/p/3636308.html
Copyright © 2011-2022 走看看