[leetcode]151. Reverse Words in a String

来源:互联网 发布:mac双系统开机默认 编辑:程序博客网 时间:2024/04/30 11:11

题目链接:https://leetcode.com/problems/reverse-words-in-a-string/#/description

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

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


class Solution {public:    // function to reverse any part of string from i to j (just one word or entire string)    void reverseword(string &s, int i, int j){        while(i<j){          char t=s[i];          s[i++]=s[j];          s[j--]=t;        }     }        void reverseWords(string &s) {                int i=0, j=0;        int l=0;        int len=s.length();        int wordcount=0;                while(true){            while(i<len && s[i] == ' ') i++;  // skip spaces in front of the word            if(i==len) break;            if(wordcount) s[j++]=' ';            l=j;            while(i<len && s[i] != ' ') {s[j++]=s[i++];}             reverseword(s,l,j-1);                // reverse word in place            wordcount++;                    }                s.resize(j);                           // resize result string        reverseword(s,0,j-1);                  // reverse whole string    }};


原创粉丝点击