码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 557. Reverse Words in a String III

时间:2017-12-15 21:31:33      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:tar   white   space   目的   test   end   相对   note   style   

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 };

 

LeetCode 557. Reverse Words in a String III

标签:tar   white   space   目的   test   end   相对   note   style   

原文地址:http://www.cnblogs.com/dapeng-bupt/p/8044805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!