Reverse words in a string Given a string, reverse each word in the string one by one.

Reverse words in
a string Given a string, reverse each word in the string one by one

Note:
No space characters form a word.
The input string can contain extra spaces before or after it, but the reversed characters cannot be included.
If there is an extra space between two words, reduce the space between the words after inversion to only one.

Example
Analysis: Before reversing the string, what we need to think about is how to remove the extra spaces between words . Here I only use the isringstream method provided in C++ (if you don’t use this method, you can use double pointers to remove spaces). Take out each word and save it in a string variable;
after removing the extra spaces, we observe that: the whole reversal once can reverse the order of the words, and then internally reverse each word to get the target string, put The above diagram↓The
Insert picture description here
code is as follows:

class Solution {
    
    
public:
	void reverse(string& str, int left, int right) {
    
    //反转字符串
		while (left < right) {
    
    
			swap(str[left++], str[right--]);
		}
	}

	string reverseWords(string& s) {
    
    
		istringstream iss(s);
		string tmp;
		string str;
		while (iss >> tmp) {
    
    
			str += tmp + ' ';
		}
		int len = str.length();
		str.erase(len - 1);//去掉末尾的' '

		int left = 0, right = len - 2;
		reverse(str, left, right);
		str += ' ';//末尾添上空格符作为标记
		right = 0;
		while (left < len) {
    
    
			while (str[right] != ' ' && right < len)
				right++;//出循环之后right停留在' '位置
			reverse(str, left, right - 1);
			left = right++ + 1;
            
		}
		str.erase(len - 1);//除去末尾的 ' '
		return str;
	}
};

Guess you like

Origin blog.csdn.net/Genius_bin/article/details/113777129