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".

    click to show clarification.

    Clarification:
    • What constitutes a word?
      A sequence of non-space characters constitutes a word.
    • Could the input string contain leading or trailing spaces?
      Yes. However, your reversed string should not contain leading or trailing spaces.
    • How about multiple spaces between two words?
      Reduce them to a single space in the reversed string.  

    没什么多说的,去空格看似挺麻烦,一次遍历就能搞定。注意最后的空格要特殊处理。

     1 class Solution {
     2 public:
     3     void reverse(string &s, int low, int high) {
     4         char tmp;
     5         while(low < high) {
     6             tmp = s[low];
     7             s[low] = s[high];
     8             s[high] = tmp;
     9             low++;
    10             high--;
    11         }
    12     }
    13     
    14     void removeBlank(string &s) {
    15         if (s.length() == 0) {
    16             return;
    17         }
    18         int count = 0;
    19         bool flag = false;
    20         for (int i = 0; i <= s.length(); ++i) {
    21             if (s[i] == ' ' && !flag) {
    22                 count++;
    23             } else if (s[i] == ' ' && flag) {
    24                 flag = false;
    25                 s[i-count] = s[i];
    26             } else if (s[i] != ' ') {
    27                 flag = true;
    28                 s[i-count] = s[i];
    29             }
    30         }
    31         int len = s.length() - count;
    32         if (s[len-1] == ' ') {
    33             s[len-1] = '';
    34             len--;
    35         }
    36         s.resize(len);
    37     }
    38 
    39     void reverseWords(string &s) {
    40         removeBlank(s);
    41         reverse(s,0,s.length()-1);
    42         int a = 0, b;
    43         for (int i=0; i<=s.length();++i){
    44             if(s[i]==' '||s[i]==''){
    45                 b = i-1;
    46                 reverse(s,a,b);
    47                 a = i+1;
    48             }
    49         }
    50         return;
    51     }
    52 };
  • 相关阅读:
    JS 笔记
    html笔记 横向两列布局
    jsp HTTP Status 405
    有效范围为request的bean
    jsp:session对象存储数据
    sql笔记
    StringBuffer的用法
    VB学习笔记
    html 笔记
    Linux 笔记
  • 原文地址:https://www.cnblogs.com/easonliu/p/3630617.html
Copyright © 2011-2022 走看看