[LeetCode][String] 186. Reverse Words in a String II

Problem

More LeetCode Discussions
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Could you do it in-place without allocating extra space?

Solution

先reverse string,之后reverse每一个word。

class Solution {
public:
    void reverseStr(string &s, int i, int j) {
        while (i < j) {
            char c = s[i];
            s[i] = s[j];
            s[j] = c;
            i++;
            j--;
        }    
    }
    
    void reverseWords(string &s) {
        if (s.size() == 0) {
            return;
        }
        
        reverseStr(s, 0, s.size() - 1);
        
        int start = 0;
        int end;
        for(int i = 0; i < s.size(); i++) {
            if (s[i] == ' ') {
                end = i - 1;
                reverseStr(s, start, end);
                start = i + 1;
            }
        }
        
        if (s[s.size() - 1] != ' ') {
            reverseStr(s, start, s.size() - 1);
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 有人看着天空流泪,有人看着小草流泪,有人看着大海流泪,有人看着花儿流泪。天空、小草、大海、花儿固然美,却剔除不掉它...
    月光下的狗尾巴草阅读 341评论 0 0
  • “怎样给孩子看书?我家孩子喜欢看小说,但我叫他看一看世界经典啊,名著啊什么的,兴趣就没那么大了,冷老师您说怎么办?...
    冷话阅读 503评论 2 1