leetcode之Reverse Words in a String

问题描述如下:

Given an input string, reverse the string word by word.

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

click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
问题链接

cpp代码如下:

class Solution {
private:
    void reverse_(string &s,int b,int e){
        for(int i=0;i<(e-b)/2;++i){
            char t=s[b+i];
            s[b+i]=s[e-1-i];
            s[e-1-i]=t;
        }
    }
public:
    void reverseWords(string &s) {
        int l=s.length();
        int b=0;
        while(b<l&&s[b]==' ')++b;
        while(l>0&&s[l-1]==' ')--l;
        int pos=0;
        while(b<l){
            if(s[b]!=' ')s[pos++]=s[b++];
            else{
                s[pos++]=' ';
                while(b<l&&s[b]==' ')++b;
            }
        }
        l=pos;
        s.resize(l);
        if(l==0)return;
        reverse_(s,0,l);
        for(int i=0,j=0;true;++i){
            if(s[i]==' '){
                reverse_(s,j,i);
                j=i+1;
            }
            else if(i==l-1){
                reverse_(s,j,l);
                break;
            }
        }
    }
};


猜你喜欢

转载自blog.csdn.net/wocaoqwerty/article/details/41723423
今日推荐