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

    Update (2015-02-12):
    For C programmers: Try to solve it in-place in O(1) space.

    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.

    反转字符串中单词的顺序。有3中可能的情况(用_表示空格):

    1. a_b

    2. __

    3. _ab

    4. ab_

    第一种情况也是最普遍的情况,检测空格并反转字符串中单词即可。

    第二、三、四种情况需要消除由1反转后多余空格。思路是将二、三种情况都转化为第四种,利用一个变量计数来统计非空格的字符数量,使用substr将最后一个空格消去

    class Solution {
    public:
        void reverseWords(string &s) {
            reverse(s.begin(), s.end());
            int tmp = 0;
            for (int i = 0; i != s.size(); i++) {
                if (s[i] == ' ') {
                    reverse(s.begin() + tmp, s.begin() + i);
                    tmp = i + 1;
                }
            }
            reverse(s.begin() + tmp, s.end());
            int t = 0;
            for (int i = 0; i != s.size(); i++) {
                if (s[i] != ' ') {
                    s[t++] = s[i];
                    if (s[i + 1] == ' ' || i == s.size() - 1)
                        s[t++] = ' ';
                }
            }
            s = s.substr(0, t == 0 ? 0 : t - 1);
        }
    };
    // 6 ms
  • 相关阅读:
    二维RMQ问题
    乘法逆元的一些求法
    对于一些小的数学的方法的一些记录
    第一次举办比赛记
    牛客网比赛-Wannafly挑战赛27
    [HEOI2012]Akai的数学作业-题解
    线性基简单学习笔记
    1978 Fibonacci数列 3
    1076 排序
    1205 单词翻转
  • 原文地址:https://www.cnblogs.com/immjc/p/7577580.html
Copyright © 2011-2022 走看看