Leetcode 115 翻转字符串里的单词

地址 https://leetcode-cn.com/problems/reverse-words-in-a-string/

给你一个字符串 s ,逐个翻转字符串中的所有 单词 。
单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。
请你返回一个翻转 s 中单词顺序并用单个空格相连的字符串。

说明:
输入字符串 s 可以在前面、后面或者单词间包含多余的空格。
翻转后单词间应当仅用一个空格分隔。
翻转后的字符串中不应包含额外的空格。

示例 1:
输入:s = "the sky is blue"
输出:"blue is sky the"

示例 2:
输入:s = "  hello world  "
输出:"world hello"
解释:输入字符串可以在前面或者后面包含多余的空格,但是翻转后的字符不能包括。

示例 3:
输入:s = "a good   example"
输出:"example good a"
解释:如果两个单词间有多余的空格,将翻转后单词间的空格减少到只含一个。

示例 4:
输入:s = "  Bob    Loves  Alice   "
输出:"Alice Loves Bob"

示例 5:
输入:s = "Alice does not even like bob"
输出:"bob like even not does Alice"

解法
字符串常规处理 处理前后缀空格,处理从字符串中摘出单词。
要注意边界条件

代码

class Solution {
public:
	string reverseWords(string s) {
		int l = 0; 
		while (l < s.size() && s[l] == ' ') l++;
		s = s.substr(l);
		int r = s.size() - 1;
		while (r >= 0 && s[r] == ' ') r--;
		s = s.substr(0, r + 1);

		r = s.size()-1;
		string ans;
		while (r >= 0) {
			while (r >= 0 && s[r] == ' ') r--;
			l = r;
			while (l >= 0 && s[l] != ' ')l--;
			int len = r - l ;
			if (l == -1) len = r + 1;
			ans += s.substr(l+1, len);
			r = l - 1;
			if(r >= 0)
				ans += ' ';
		}

		return ans;
	}
};
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/15105012.html