zoukankan      html  css  js  c++  java
  • [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 };
  • 相关阅读:
    Linux Bash管理
    Linux文件查看
    Linux文件目录
    yum Linux软件安装工具
    第十六、十七天,关于面向对象
    第十四天,内置函数
    第十二天
    第十一天
    第十天
    第九天(开始函数)
  • 原文地址:https://www.cnblogs.com/skycore/p/3991550.html
Copyright © 2011-2022 走看看