文章目录
- 1. 题目
- 2. 解题
1. 题目
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]注意:
单词的定义是不包含空格的一系列字符
输入字符串中不会包含前置或尾随的空格
单词与单词之间永远是以单个空格隔开的进阶:使用 O(1) 额外空间复杂度的原地解法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 先整体反转一遍
- 然后找到每个单词,逐个单词反转
- 原地,O(1) 空间复杂度
class Solution {
public:void reverseWords(vector<char>& s) {reverse(s, 0, s.size()-1);int l = 0, r;while(r < s.size()){while(r < s.size() && s[r]!=' ')//没遇见分隔符r++;reverse(s, l, r-1);r++;//跳过空格l = r;}}void reverse(vector<char>& s, int l, int r){while(l < r)swap(s[l++],s[r--]);}
};
64 ms 17.3 MB
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!