• [LeetCode]Reverse Words in a String


    题目描述:

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

    For example,
    Given s = "the sky is blue",
    return "blue is sky the".

    解决方案:

    该题目解决思路很简单,新建一个字符串,然后对于给定字符串,从后向前遍历,遇到一个单词就加到新建的字符串中,别忘了加空格。当然提前还得去除给定字符串首尾的空白符号。下面是该题的代码:

     1 class Solution {
     2 public:
     3     void reverseWords(string &s) {
     4         int i = 0;
     5         int j = s.size() - 1;
     6         string str;
     7         for(; s[i] == ' '; ++i);
     8         for(; s[j] == ' '; --j);
     9 
    10         int temp;
    11         for(temp = j; temp >= i; --temp){
    12             if (s[temp] == ' ' && s[temp + 1] != ' '){
    13                 str.append(s, temp + 1, j - temp);
    14                 str.append(1, ' ');
    15             }
    16             if (s[temp] != ' ' && s[temp + 1] == ' ') {
    17                 j = temp;
    18             }
    19         }
    20         str.append(s, temp + 1, j - temp);
    21         s = str;
    22     }
    23 };
  • 相关阅读:
    装饰器详解
    面试题求 平衡点
    Python面试题
    With语句上下文管理
    多个装饰器修饰一个函数
    NGINX部署配置参考.
    Django ORM操作
    MYsql 之多表查询.
    [数据结构与算法] : 二叉查找树
    [数据结构与算法] : 队列
  • 原文地址:https://www.cnblogs.com/skycore/p/3991550.html
Copyright © 2020-2023  润新知