LeetCode151 Reverse Words in a String 反转字符串中的字

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

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

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

Example 3:

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.

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

题源:here;完整实现:here

思路:

我们将字符串中的每个字单独存下来,然后在依次反向输出即可。

class Solution {
public:
	string reverseWords(string s) {
		vector<string> tmp;
		string word;
		s += ' ';
		for (auto i : s) {
			if (isspace(i)) {
				if (!word.empty()) tmp.push_back(word);
				word = "";
			}
			else {
				word += i;
			}
		}

		if (tmp.empty()) return word;
		string res;
		for (auto it = tmp.end() - 1; it != tmp.begin(); it--) {
			res += *it + ' ';
		}
		res += tmp.front();
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88031326