zoukankan      html  css  js  c++  java
  • LeetCode: 557Reverse Words in a String III(easy)

    题目:

    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.

    代码:

     1 class Solution {
     2 public:
     3     string reverseWords(string s) {
     4         stack<char> tem;
     5         string result;
     6         string s1 = s + ' ';
     7         for (auto c : s1){
     8             if ( c != ' ')
     9                 tem.push(c);
    10             else {
    11                 while(!tem.empty()){
    12                     result = result + tem.top();
    13                     tem.pop();
    14                 }
    15                 result = result + ' ';
    16             }
    17         }
    18         result = result.substr(0, result.length()-1);
    19         return result;
    20     }
    21 };

    运行时间:772ms

    别人的:

     1 class Solution {
     2 public:
     3     
     4     string reverseWords(string s) {
     5         string result(s.length(), 32);
     6         int start = 0;
     7         int end = s.find(32);
     8         while (end != -1) {
     9             for (int i = start; i < end; ++i)
    10                 result[end - (i - start) - 1] = s[i];
    11             start = end + 1;
    12             end = s.find(32, start);
    13         }
    14         end = s.length();
    15         for (int i = start; i < end; ++i)
    16             result[end - (i - start) - 1] = s[i];
    17         return result;
    18     }
    19 };

    运行时间:26mm

    栈比较耗时间?

  • 相关阅读:
    C语言_航模社第四节
    C语言_航模社第三节
    C语言交换两个变量的值
    C语言表达分段函数
    c语言_2017.10.22
    stm32_配置GPIO点亮led灯
    prteus8安装教程
    安装keil_5步骤
    nginx配置实现https的配置文件方法
    TortoiseGit 代码版本回退及返回
  • 原文地址:https://www.cnblogs.com/llxblogs/p/7404853.html
Copyright © 2011-2022 走看看