• LeetCode 557. Reverse Words in a String III


    Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

    Example 1:

    Input: "Let's take LeetCode contest"
    Output: "s'teL ekat edoCteeL tsetnoc"
    

    Note: In the string, each word is separated by single space and there will not be any extra space in the string.

    题目的要求很简单,要求翻转每个单词,但是保持空格以及单词的相对顺序不变,最开始我想的是用一个栈,遇见空格把栈中的单词弹出,最后也确实AC了,代码如下:

     1 class Solution {
     2 public:
     3     string reverseWords(string s) {
     4         stack<char> sta;
     5         //s += ' ';
     6         string res = "";
     7         for (int i = 0; i <= s.length(); i++)
     8         {
     9            if (s[i] != ' ' && i != (s.length()))
    10            //if (s[i] != ' ')
    11             {
    12                 sta.push(s[i]); 
    13                 //cout<<sta.top()<<endl;
    14             }
    15             else
    16             {
    17                while (!sta.empty())
    18                {
    19                  res += sta.top();
    20                  //std::cout<<sta.top();
    21                  sta.pop();
    22                }
    23                if (s[i] == ' ')
    24                  res += ' ';
    25             }
    26         }
    27         cout<<endl;
    28         return res;
    29     }
    30 };

    当然也可以使用reverse函数,代码如下:

    class Solution {
    public:
        string reverseWords(string s) {
            int front = 0;
            for (int i = 0; i <= s.length(); i++)
            {
                if (s[i] == ' ' || i == s.length())
                {
                    reverse(&s[front], &s[i]);
                front = i + 1;
                }
                    
            }
            return s;
        }
    };

    或者是使用两个指针,分别指向字符串的 头和尾部:

     1 class Solution {
     2 public:
     3     string reverseWords(string s) {
     4         int start = 0, end = 0, n = s.size();
     5         while (start < n && end < n) {
     6             while (end < n && s[end] != ' ') ++end;
     7             for (int i = start, j = end - 1; i < j; ++i, --j) {
     8                 swap(s[i], s[j]);
     9             }
    10             start = ++end;
    11         }
    12         return s;
    13     }
    14 };
  • 相关阅读:
    宝藏 题解
    Xorequ 题解
    2020.12.26 模拟赛 题解
    数据结构 100 题 1~10 线段树
    关于模拟退火
    诗意狗 题解
    Keyboading 思路
    体育成绩统计/ Score
    【(抄的)题解】P5686 [CSP-SJX2019]和积和
    【笔记】简单博弈
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8044805.html
Copyright © 2020-2023  润新知