zoukankan      html  css  js  c++  java
  • 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.

    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,被空格包围的是单词

    2,输入字符串可以以空格开头或结尾,但是结果中的字符不能以空格开头或结尾

    3,输出字符串中单词间的空格是一个,不能重复出现空格.

    思路:

    对输入字符串进行去重空格操作,

    对字符串中的每个单词进行反转

    对整个字符串进行反转

    ====

    code

    class Solution {
    public:
        void help_reverse(string &s,int start,int end){
            while(start<end){///经典的反转字符串方法
                swap(s[start++],s[end--]);
            }
        }
        string removeDuplicateSpace(string s){
            string res;
            int b = 0;
            for(;b<(int)s.size();b++){
                if(s[b]!= ' '){
                    break;
                }
            }///
            int e = s.size() - 1;
            for(;e>=0;e--){
                if(s[e]!=' '){
                    break;
                }
            }
    
            bool is_space = false;
            for(int i = b;i<=e;i++){
                if(s[i] == ' '){
                    if(!is_space) is_space = true;
                    else continue;
                }else{
                    is_space = false;
                }
                res.push_back(s[i]);
            }
            return res;
        }
        void reverseWords(string &s) {
            if(s.empty()) return;
            s = removeDuplicateSpace(s);
            int start = 0;
            for(size_t i = 0;i<s.size();i++){
                if(s[i]!=' '){
                    start = i;
                }else{
                    continue;
                }
                size_t j = i;
                while(j<s.size() && s[j]!=' '){
                    j++;
                }
                j--;
                help_reverse(s,start,j);
                i = j++;
            }
            help_reverse(s,0,(int)s.size()-1);
        }
    };
  • 相关阅读:
    DeepWalk论文精读:(2)核心算法
    DeepWalk论文精读:(3)实验
    DeepWalk论文精读:(1)解决问题&相关工作
    面向对象第四单元(UML)总结
    面向对象第三单元(地铁)总结
    面向对象第二单元(电梯)总结
    面向对象第一单元(多项式求导)总结
    我的2017年总结
    【转】胡侃学习(理论)计算机
    当当图书又打折?
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5608282.html
Copyright © 2011-2022 走看看