[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 input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.

3.How about multiple spaces between two words?
Reduce them to a single space in the reversed string.

  • 解题思路1
    • 因为是要得到逆序的单词组合,所以从字符串头部开始遍历,把解析得到的单词放到一个栈中,最后把栈中的单词出栈连接成一个字符串。
    • 遍历过程中,如果某个单词的后面有空格,则在其前面增加一个空格。由于最后一个单词后面也有可能有空格,所以检查最后得到的字符串的第一个字符,如果是空格,则清除它。
  • 实现代码1
/*****************************************************************
    *  @Author   : 楚兴
    *  @Date     : 2015/2/9 11:05
    *  @Status   : Accepted
    *  @Runtime  : 13 ms
******************************************************************/
class Solution {
public:
    void reverseWords(string &s) {
        string temp;
        stack<string> mystack;
        int i = 0;
        while (i < s.size())
        {
            if(s[i] == ' ')
            {
                if (temp.compare(""))
                {
                    //在得到的单词前面增加空格
                    temp.insert(temp.begin(), ' ');
                    mystack.push(temp);  //单词入栈
                    temp = "";  //单词重置为空
                    i++;
                }
                while (i < s.size() && s[i] == ' ')
                {
                    i++;
                }
            }
            else
            {
                temp += s[i];
                i++;
            }
        }
        if (temp.compare(""))
        {
            mystack.push(temp);  //最后得到的单词不为空,则入栈
        }

        s = "";
        while (!mystack.empty())
        {
            s += mystack.top();  //重新组合单词
            mystack.pop();
        }

        if (s.compare("") && s[0] == ' ')
        {
            s.erase(s.begin());  //如果新字符串以空格开头,则清除空格
        }
    }
};
  • 解题思路2
    从后往前遍历,遇到空格时单词结束。省去了栈的使用。
  • 实现代码2
/*****************************************************************
    *  @Author   : 楚兴
    *  @Date     : 2015/2/9 14:04
    *  @Status   : Accepted
    *  @Runtime  : 10 ms
******************************************************************/
class Solution {
public:
    void reverseWords(string &s) {
        string result = "";
        string temp = "";
        int i = s.size() - 1;
        while (i >= 0)
        {
            if (s[i] == ' ')
            {
                if (temp.compare(""))
                {
                    temp.push_back(' ');
                    reverse(temp.begin(),temp.end());
                    result.append(temp);
                    temp = "";
                    i--;
                }
                while (i >= 0 && s[i] == ' ')
                {
                    i--; //去除多余空格
                }
            }
            else
            {
                temp.push_back(s[i]);
                i--;
            }
        }
        if (temp.compare(""))
        {
            temp.push_back(' ');
            reverse(temp.begin(),temp.end());
            result.append(temp);
        }

        if (result.size() > 0 && result[0] == ' ')
        {
            result.erase(result.begin()); //去除字符串开头的空格
        }

        s = result;
    }
};
时间: 2024-10-25 06:18:05

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

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

[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]--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] Reverse Linked List(递归与非递归反转链表)

Reverse a singly linked list. 解题思路 对于非递归实现,思路是依次将从第二个结点到最后一个结点的后继设为头结点,然后将该节点设为头结点(需记住将原头结点的后继设为空). 对于递归实现,首先反转从第二个结点到最后一个结点的链表,然后再将头结点放到已反转链表的最后,函数返回新链表的头结点. 非递归实现代码1[C++] //Runtime:10 ms class Solution { public: ListNode* reverseList(ListNode* head

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". click to show clarification. Clarification:   What constitutes a word?A sequence of non-space characters constitu

[LeetCode] 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 ≤ le

[LeetCode] Reverse Bits

1Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). Follow up: If this functio

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