您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页[LeetCode][String] 186. Reverse

[LeetCode][String] 186. Reverse

来源:华佗小知识

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

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务