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

    栈比较耗时间?

  • 相关阅读:
    go if 判断 完成随机分数的评级
    go for循环
    go 常量2
    go 常量定义和使用
    更新数据库某字段数据为流水号
    BPM设定操作超时
    BPM打印按钮
    BPM链接处理
    项目管理
    公司规划
  • 原文地址:https://www.cnblogs.com/llxblogs/p/7404853.html
Copyright © 2011-2022 走看看