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

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.

思路

两次反转法。这里注意单词之间的多个空格只留一个空格以及去掉前导0和后导0。

代码

/*---------------------------------------
*   日期:2015-05-05
*   作者:SJF0115
*   题目: 151.Reverse Words in a String
*   网址:https://leetcode.com/problems/reverse-words-in-a-string/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    void reverseWords(string &s) {
        int size = s.size();
        if(size <= 0){
            return;
        }//if
        // 前导0
        int index = 0;
        while(s[index] == ' '){
            ++index;
        }//while
        int left = index;
        // 后导0
        index = size - 1;
        while(s[index] == ' '){
            --index;
        }//while
        int right = index;
        // 连续空格只保留一个
        for(int i = left;i <= right;){
            if(i > left && s[i-1] == ' ' && s[i] == ' '){
                s.erase(i-1,1);
                --right;
            }//if
            else{
                ++i;
            }
        }//for
        // 翻转
        int start = left,end = left;
        for(int i = left;i <= right+1;++i){
            if(i == right+1 || s[i] == ' '){
                Reverse(s,start,end-1);
                ++end;
                start = end;
            }//if
            else{
                ++end;
            }//else
        }//for
        // 整体翻转
        Reverse(s,left,right);
        s = s.substr(left,right - left + 1);
    }
private:
    void Reverse(string &str,int start,int end){
        for(int i = start,j = end;i < j;++i,--j){
            swap(str[i],str[j]);
        }//for
    }
};

int main() {
    Solution solution;
    //string str("   abc    cd     ef ");
    string str("  a   vvv  ");
    solution.reverseWords(str);
    cout<<str<<endl;
}

运行时间

代码二

/*---------------------------------------
*   日期:2015-05-05
*   作者:SJF0115
*   题目: 151.Reverse Words in a String
*   网址:https://leetcode.com/problems/reverse-words-in-a-string/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <algorithm>
using namespace std;

class Solution {
public:
    void reverseWords(string &s) {
        int size = s.size();
        if(size <= 0){
            return;
        }//if
        int index = size - 1;
        string str;
        while(index >= 0){
            // 空格
            while(index >= 0 && s[index] == ' '){
                --index;
            }//while
            if(index < 0){
                break;
            }//if
            if(str.size() != 0){
                str.push_back(' ');
            }//if
            string tmp;
            while(index >= 0 && s[index] != ' '){
                tmp.push_back(s[index]);
                --index;
            }//while
            // 翻转
            reverse(tmp.begin(),tmp.end());
            str.append(tmp);
        }//while
        s = str;
    }
};

int main() {
    Solution solution;
    string str("   abc    cd     ef ");
    //string str(" a  ");
    solution.reverseWords(str);
    cout<<str<<endl;
}

运行时间

时间: 2024-10-02 06:49:23

[LeetCode]151.Reverse Words in a String的相关文章

[LeetCode]--345. Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode", return "leotcede". Note: The vowels does not incl

[LeetCode 第3题] -- Reverse Words in a String

题目链接: Reverse Words in s String 题目意思: 给定一个字符串,要求把字符串中的"单词"反转                 1. 所谓"单词"指的的连续的非空白字符                 2. 必须把前后缀空格去掉                 3. 连续多个空格要合并为一个 代码 class Solution { public: void reverseWords(string &s); }; void Solut

LeetCode 7 Reverse Integer(翻转整数)

翻译 翻转一个整型数 例1:x = 123, 返回 321 例2:x = -123, 返回 -321 原文 Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Have you thought about this? (来自LeetCode官网) Here are some good questions to ask before coding. Bonus poi

leetcode 22 Generate Parentheses关于C++ string的问题

问题描述 leetcode 22 Generate Parentheses关于C++ string的问题 /* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())

[LeetCode] Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode", return "leotcede". 解题思路 双指针,一个往前移动,一个往后移动,找到元音字母时

[LeetCode] 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". Clarification: 1.What constitutes a word? A sequence of non-space characters constitutes a word. 2.Could the in

[LeetCode]--344. Reverse String

Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". public String reverseString(String s) { char[] ss = s.toCharArray(); int j = ss.length - 1, i = 0; char temp; wh

[LeetCode]--190. Reverse Bits(不是很懂的位运算)

补充知识,Java的位运算(bitwise operators) Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000

[LeetCode]92.Reverse Linked List II

[题目] Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n