zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    面向对象的设计原则
    在VC中Debug下是运行结果正确的,但是在Release下却有错,总算找到原因
    聚合和组合
    痛苦呀,代码
    MSDN和VS98
    阅读代码的难度
    好香,方便面
    人的重要性
    FIT For .NET(1)
    ASP.NET Microsoft .NET Pet Shop 3.x(二)
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8044805.html
Copyright © 2011-2022 走看看