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

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

    思路:先去掉前面多余的空格,然后去掉中间多余的空格用快慢指针实现,然后反转。

    class Solution {
    public:
        void reverseWords(string &s) {
            int n = s.size();
            int i = 0, j = 0;
            while (j < n) {
                while (j < n && s[j] == ' ') j++;             // 跳过前面空格
                while (j < n && s[j] != ' ') s[i++] = s[j++]; // 保留字母
                while (j < n && s[j] == ' ') j++;             // 跳过中间空格
                if (j < n) s[i++] = ' ';                      // 添加中间的一个空格
            }
            s = s.substr(0, i);
            reverse(s.begin(), s.end());
            int b = 0;
            cout << s << endl;
            for (int i = 0; i < s.size(); ++i) {
                if (s[i] == ' ') {
                    reverse(s.begin() + b, s.begin() + i);
                    b = i+1;
                }
            }
            reverse(s.begin()+b, s.end());
        }
    };
    
  • 相关阅读:
    yii2之依赖注入与依赖注入容器
    MySQL查询性能优化
    MySQL索引(2)
    go es
    es数据操作入门
    es环境搭建
    gRPC接入etcd
    etcd简单介绍
    Go调用NSQ简单实践
    NSQ快速入门实践
  • 原文地址:https://www.cnblogs.com/pk28/p/8483598.html
Copyright © 2011-2022 走看看