LeetCode-151 Reverse Worlds in a String

题目描述

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

题目大意

输入一个字符串,将字符串中的单词按倒序排列(单词中的字母不要倒叙排列)。

示例

E1

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

E2

Input: "  hello world!  "
Output: "world! hello"

E3

Input: "a good   example"
Output: "example good a"

解题思路

遍历一遍字符串即可,遍历过程中保存该遍历位置不为空格的字符,若遇到空格跳过即可,每次将获得的空格之间的子字符串插入到结果的首位即可。

复杂度分析

时间复杂度:O(n)

空间复杂度:O(n)

代码

class Solution {
public:
    string reverseWords(string s) {
        string ans = "";
        //遍历字符串
        for(int i = 0; i < s.length(); i++) {
            string temp = "";
            //查找符合条件的子字符串并保存
            int j = i;
            while(j < s.length() && s[j] != ' ') {
                temp += s[j];
                j++;
            }
            if(temp.length())
                ans.insert(0, (temp + ' '));
            i = j;
        }
        //删除答案最后多余的空格符
        ans.pop_back();
        
        return ans;
    }
};
原文地址:https://www.cnblogs.com/heyn1/p/10937293.html