zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    第07组 Alpha冲刺(1/6)
    第07组 团队Git现场编程实战
    第07组 团队项目-需求分析报告
    团队项目-选题报告
    第二次结对编程作业
    0012---求滑动距离
    0011---绝对值函数
    0010---温度转换
    0009---乘法问题
    0008---三位数倒序问题
  • 原文地址:https://www.cnblogs.com/heyn1/p/10937293.html
Copyright © 2011-2022 走看看