[Leetcode]Reverse Words in a String

原创 2015年11月18日 00:08:17

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.

class Solution {
public:
    /*algorithm
        reverse whole sentence
        reverse word by word
        time O(n) space O(1)
    */
    void reverse(string &s,int start,int len){
        int i = 0,j = len-1;
        while(i < j){
            swap(s[start+i],s[start+j]);
            i++,j--;
        }
    }
    void reverseWords(string &s) {
        //space pre-process,remove leading and trailing spaces,reduce words space to 1 
        int k = 0;
        for(int i = 0;i < s.size();i++){
           if(s[i] != ' '){
             if(i&&s[i-1]==' '&&k)s[k++] = ' ';  
             s[k++] = s[i];                                 
           }  
        }
        s.resize(k);
        
        reverse(s,0,s.size());
        for(int i = 0;i < s.size();){
            int j = i;
            while(j+1 < s.size() && s[j+1] != ' ')++j;
            reverse(s,i,j-i+1);
            i = j+2;
        }
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

将一个英文句子单词顺序逆置(LeetCode | Reverse Words in a String)

题目: Given an input string, reverse the string word by word. For example, Given s = "the sky...

[LeetCode186]Reverse Words in a String II

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space...

[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", ret...

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”, ...

《leetCode》:Reverse Words in a String

题目Given an input string, reverse the string word by word.For example, Given s = "the sky is blue", r...

LeetCode之186_Reverse Words in a String 字符串词序反转算法

给定一个字符串S,反转其中存在的单词顺序,将

[leetcode]151. Reverse Words in a String@Java解题报告

https://leetcode.com/problems/reverse-words-in-a-string/tabs/description Given an input s...

LeetCode OJ 之 Reverse Words in a String (翻转字符串的单词)

题目: Given an input string, reverse the string word by word.(给定一个输入字符串,按单词翻转这个字符串) For exampl...

LeetCode 之 Reverse Words in a String — C 实现

Reverse Words in a String   Given an input string, reverse the string word by word. For example, ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)