zoukankan      html  css  js  c++  java
  • 151. Reverse Words in a String (String)

    思路: 本题考查的目的并不是使用字符串的函数。方法是两次reverse,先对每个单词先做一次翻转,然后对整个字符串做一次翻转。

    需要注意的是去除extra space,并且对全space字符串、以及最后一个单词要做特殊处理。

    class Solution {
    public:
        void reverseWords(string &s) {
            int start = 0;
            int end=-1;
            int i = 0;
            int cur = 0; // point to the string with extra space deleted
            
            //ignore space at the beginning
            while(i < s.length() && s[i]==' '){
                i++;
            }
            
            for(;i<s.length();i++){
                if(s[i]==' ' && i+1 < s.length() && s[i+1] ==' ') continue; //ignore extra space between words
                if(s[i]==' ' && i+1 == s.length()) break; //ignore final space
                s[cur++] = s[i];
                if(s[i]==' '){
                    end = cur-2; //end case1: the letter before space 
                    reverse(s, start, end);
                    start = cur;
                }
            }
            end = cur-1; //end case2: the last not space letter!!!
            if(end == -1) s = ""; //special case: null string!!!
            if(s[i-1] != ' '){ //reverse the last word!!!
                reverse(s,start,end);
            }
            cout << "end=" << end << endl;
            s = s.substr(0, end+1);
            reverse(s,0,end);
        }
        
        void reverse(string &s, int start, int end){
            int l = start;
            int r = end;
            char tmp;
            while(l<r){
                tmp = s[l];
                s[l]=s[r];
                s[r]=tmp;
                l++;
                r--;
            }
        }
    };
  • 相关阅读:
    jQuery使用工具集
    JQuery解决鼠标单双击冲突问题
    线程池
    配置文件application.properties参数详解
    SpringBoot整合SpringDataJPA
    获取数据库的自增主键(六)
    【使用篇二】邮箱自动化配置集成(18)
    Quartz自动化配置集成
    Cron表达式详解
    标准盒模型和怪异盒模型的区别
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/6152819.html
Copyright © 2011-2022 走看看