• 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 };
  • 相关阅读:
    将博客搬至CSDN
    U盘启动盘 安装双系统 详细教程
    vmware安装linux6.3
    hadoop学习之路
    linux重定向总结:如何将shell命令的输出信息自动输出到文件中保存
    AVRO讲解
    MapReduce 工作原理
    lucene索引存储原理
    ES数据库系统
    分流器设备与交换机设备的区别
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6838231.html
Copyright © 2020-2023  润新知