Leetcode-151.Reverse Words in a String

Problem Description:
Given an input string, reverse the string word by word.

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


Analysis:
This is probably by far the most common string manipulation interview question.
The idea to solve the problem is : First delete all the extra spaces, then reverse all the characters in the string, then reverse the letters of each word. For trim job, we need to pointers.

O(1) space solution :

class Solution {
public:
    void reverseWords(string& s) {
        trim(s);//remove the whitespace and reverse.
        int l = 0;
        for (int i = 0; i < s.size(); ++i)
        {
            if (s[i] == ' ')
            {
                reverse(s.begin() + l, s.begin() + i);
                l = i + 1;
            }
        }
        reverse(s.begin() + l, s.end());// we need one more operation to reverse the last word. OR  we could add a extra ' ' to the end, delete it when finish.
        return;
    }

    void trim (string& s)
    {
    int i;
    int n = s.size();
    for (i = n - 1; i >= 0 && s[i] == ' '; --i){}
    s = s.substr(0, i + 1);
    reverse(begin(s), end(s));
    for (i = s.size() - 1; i >= 0 && s[i] == ' '; --i){}
    s = s.substr(0, i + 1);
    n = s.size();
    int tail = 0;
    for (i = 0; i < n;)
    {   
        if (s[i] != ' ' || (s[i] == ' ' && s[i - 1] != ' '))
            s[tail++] = s[i];
        i++;
    }
    s = s.substr(0, tail);// remove the traling spaces or  s.resize(tail);  
    return ;
}
};

Other short code :
O(N) both space and time complexity

void reverseWords(string &s) {
    istringstream is(s);
    string tmp;
    is >> s;
    while(is >> tmp) s = tmp + " " + s;
    if(s[0] == ' ') s = "";
}

Python code

def reverseWords1(text): 
    print " ".join(reversed(text.split())) 
    print " ".join(text.split()[::-1])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值