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.


思路:找到空格(或者末尾,此时无空格),对范围内的单次进行reverse,先入后出,想到stack。

知识点:string和stack的使用

http://www.cplusplus.com/reference/stack/stack/

http://www.cplusplus.com/reference/string/string/

代码1:

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

代码2:

class Solution {
public:
    string reverseWords(string s) {
        stack<char> st;
        string res;
        st.push(' ');
        for(char ch:s){
            if(ch==' '){
                while(st.size()>0){
                    char temp;
                    temp=st.top();
                    st.pop();
                    res.push_back(temp);
                }
                st.push(' ');
            }
            else{st.push(ch);}
        }
        //最后一次无空格,所以得单独处理
        while(st.size()>1){
            char temp;
            temp=st.top();
            st.pop();
            res.push_back(temp);
        }
        return res;
    }
};
代码3:

class Solution {
public:
    string reverseWords(string s)
    {
        int spaceIdx = -1;
        const int n = s.size();
        for (int i = 0; i < n; i++)
        {
            if (s[i] == ' ' || i == n - 1)
            {
                if (i == n - 1)
                    i++;
                int l = spaceIdx + 1;
                int r = i - 1;
                while (l < r)
                    swap(s[l++], s[r--]);
                spaceIdx = i;
            }
        }
        return s;
    }
};
头文件:<utility>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值