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

 

栈比较耗时间?

posted on 2017-08-21 15:53  玲珑子  阅读(108)  评论(0编辑  收藏  举报

导航