[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

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;
    }
};
目录
相关文章
|
10月前
|
算法 C++
【LeetCode】【C++】string OJ必刷题
【LeetCode】【C++】string OJ必刷题
49 0
CF1553B Reverse String(数学思维)
CF1553B Reverse String(数学思维)
35 0
|
5月前
|
机器学习/深度学习 canal NoSQL
从C语言到C++_12(string相关OJ题)(leetcode力扣)
从C语言到C++_12(string相关OJ题)(leetcode力扣)
46 0
|
5月前
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
5月前
|
Go 机器学习/深度学习 Rust
Golang每日一练(leetDay0119) 反转字符串I\II Reverse String
Golang每日一练(leetDay0119) 反转字符串I\II Reverse String
79 0
Golang每日一练(leetDay0119) 反转字符串I\II Reverse String
|
11月前
|
Java
Leetcode 467. Unique Substrings in Wraparound String
大概翻译下题意,有个无限长的字符串s,是由无数个「abcdefghijklmnopqrstuvwxy」组成的。现在给你一个字符串p,求多少个p的非重复子串在s中出现了?
43 0
|
算法 索引
【LeetCode】string 类的几道简单题
【LeetCode】string 类的几道简单题
【LeetCode】string 类的几道简单题
LeetCode 438. Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter.
85 0
LeetCode 438. Find All Anagrams in a String
|
存储
LeetCode 394. Decode String
给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
88 0
LeetCode 394. Decode String
|
索引
LeetCode 387. First Unique Character in a String
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
101 0
LeetCode 387. First Unique Character in a String