zoukankan      html  css  js  c++  java
  • Leetcode 557. 反转字符串中的单词 III

    1.题目描述

    给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

    示例 1:

    输入: "Let's take LeetCode contest"
    输出: "s'teL ekat edoCteeL tsetnoc" 

    注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

    2.一般解法

    class Solution {
    public:
        string reverseWords(string s) {
            if(s.size()==0) return s;
            
            //拷贝字符串
            for(auto a : s)
                res.push_back(a);//string也支持vector的push_back操作
            
            //遍历寻找空格
            int size = s.size();
            int begin = 0;
            for(int i=0; i<size; ++i){
                if(s[i]==' ')
                {
                    reverse(res,begin,i-1);
                    begin = i+1;
                }
            }
            //反转最后一个单词(for循环中未处理)
            reverse(res,begin,size-1);
            return res;        
        }
        
        //反转函数
        void reverse(string& s, int begin, int end){
            for(int m=begin; m<=(begin+end)/2; ++m)
                swap(s[m],s[begin+end-m]);
        }
        
    private:
        string res;
    };

    3.优化代码

    //推荐:迭代器放方式访问
    class Solution {
    public:
        string reverseWords(string s) {
            auto beg = s.begin(), end = s.begin();
            while(beg != s.end()) {
                while(beg != s.end() && *beg != ' ')
                    ++beg;
                reverse(beg,end);//直接调用系统的reverse函数
                if(beg!=s.end()) end= ++beg;
            }
            return s;
        }
    };
  • 相关阅读:
    Redis 连接
    Redis 脚本
    Redis 事务
    Redis 发布订阅
    redis 字符串数据(string)
    Redis 键(key)
    Redis 命令
    Redis的五种数据类型
    java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory 解决方案
    在命令行中运行eclipse中创建的java项目
  • 原文地址:https://www.cnblogs.com/paulprayer/p/10132691.html
Copyright © 2011-2022 走看看