151. Reverse Words in a String(Leetcode每日一题-2020.04.10)

Problem

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

Example1

Input: “the sky is blue”
Output: “blue is sky the”

Example2

Input: " hello world! "
Output: “world! hello”
Explanation: Your reversed string should not contain leading or trailing spaces.

Example3

Input: “a good example”
Output: “example good a”
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Solution

需要去除首位的空字符

翻转整个string

双指针,依次翻转每个单词,去除单词中间多余的空格

class Solution {
public:
    string reverseWords(string s) {
        int length = s.length();
		reverse(s.begin(),s.end());

		int read = 0;
		int write = 0;
		while(read < length)
		{
		    //skip leading white space and more than one white spaces between words
			if(s[read] == ' ')
				++read;
			else
			{
			    //record the start of a word
				int wordStart = read;
				//count the length of a word
				while(read < length && s[read] != ' ')
					++read;
				//reverse  current word	
				reverse(s.begin() + wordStart,s.begin() + read);
				//copy current word to the appropriate position
				copy(s.begin() + wordStart,s.begin() + read,s.begin() + write);
				//move write to the end of current word
				write += read - wordStart;
				//add white space between words
				if(write < length)
					s[write] = ' ';
				//move write one step forward	
				++write;
			}
		}
		//s is not a empty string or string of white spaces
       if (write)
		{
			s = s.substr(0,write-1);
		}
		else
			s = "";

        return s;
    }
};
发布了547 篇原创文章 · 获赞 217 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105443599