Skip to content
MisakaTang's Blog
Go back

LeetCode刷题--557. Reverse Words in a String III

Edit page

题目及理解

题目连接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.

理解

水题,就是按照每个单词进行翻转.我的方法是遇到空格之前都压入栈中,然后遇到空格全部pop出来,结果自己僵化,最后没有空格的时候没有把最后一个单词pop出来,这里需要注意一下.

代码

class Solution {
    public:    
        string reverseWords(string s) {        
            string news;        
            stack<char> stack;        
            for (int i=0; i<s.size(); i++){            
                stack.push(s[i]);            
                if (stack.top() == ' '){                
                    stack.pop();                
                    while(!stack.empty()){                    
                        news += (char)stack.top();                    
                        stack.pop();                
                    }                
                    news += ' ';            
                }        
            }        
            while(!stack.empty()){                    
                news += (char)stack.top();                    
                stack.pop();                
            }        
        return news;    
    }
};

其他解法

看了别人dalao写的代码,用的是找空格然后整体翻转的思路,但是我这样写比较偷懒吧= =

class Solution {
    public:    
        string reverseWords(string s) {        
            for (int i = 0; i < s.length(); i++) {            
                if (s[i] != ' ') {   // when i is a non-space
                    int j = i;                
                    for (; j < s.length() && s[j] != ' '; j++) { }  // move j to the next space                
                    reverse(s.begin() + i, s.begin() + j);                
                    i = j - 1;            
                }        
            }                
        return s;    
    }
};

Edit page
Share this post on:

Previous Post
MIT_CS6.00笔记Lec1-3
Next Post
Django学习--Writing your first Django app(5)