zoukankan      html  css  js  c++  java
  • leetcode【151】-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".

    思路:

    一个字符一个字符的遍历:

      遇到非空字符->①继续向后遍历

      遇到空字符->①单词入栈;②继续向后遍历

    需要的变量:

      flag:ture状态下遇到空格可将单词入栈;false状态下遇到空格,说明前面是连续的空格,需继续向后遍历;

      beginpos:单词起始位置;

      word:栈,用于存放单词;

     1 #include<string>
     2 #include<stack>
     3 using namespace std;
     4 
     5 
     6 class Solution {
     7 public:
     8     void reverseWords(string &s) {
     9         stack<string> word;
    10         int i = 0;
    11         bool flag = false;
    12         int beginpos = 0;
    13         while (i <= s.size()){
    14             if (0 == i){
    15                 if (s[i] != ' '){
    16                     beginpos = 0;
    17                     flag = true;
    18                 }
    19             }
    20             else if (i < s.size()){
    21                 if (s[i] == ' '){
    22                     if (flag){
    23                         if (word.empty()){
    24                             word.push(s.substr(beginpos, i - beginpos));
    25                         }
    26                         else{
    27                             word.push(" ");
    28                             word.push(s.substr(beginpos, i - beginpos));
    29                         }
    30                         flag = false;
    31                     }
    32                 }
    33                 else{
    34                     if (flag == false){
    35                         beginpos = i;
    36                         flag = true;
    37                     }
    38                 }
    39             }
    40             else if (i == s.size()){
    41                 if (flag){
    42                     if (word.empty()){
    43                         word.push(s.substr(beginpos, i - beginpos));
    44                     }
    45                     else{
    46                         word.push(" ");
    47                         word.push(s.substr(beginpos, i - beginpos));
    48                     }
    49                 }
    50             }
    51             ++i;
    52         }
    53         s.clear();
    54         while (!word.empty()){
    55             s+=word.top();
    56             word.pop();
    57         }
    58     }
    59 };
  • 相关阅读:
    php入门变量
    php入门引言
    帝国cms7.0修改默认搜索模版中的分页[!--show.page--]
    帝国cms 列表页分页样式修改美化【2】
    划词翻译
    MySQL几种常见的排序方式
    你的眼界决定了你的格局
    Easy Window Switcher支持Windows 10虚拟桌面
    鬼谷子的人生智慧
    接口设计的八大黄金规则
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6838231.html
Copyright © 2011-2022 走看看