【LeetCode】20.Array and String — Reverse Words in a String 反转字符串中的单词

Given an input string, reverse the string word by word.

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up:

For C programmers, try to solve it in-place in O(1) extra space.

个人认为,本题的关键有两点:①单词的提取@空白字符的处理。在该方法中,基本思路是遍历字符串,如果遇到空白字符即跳过(i++),当遇到非空白字符时候,设置计数器(counter++),用于保存每一个字母进而通过string类特头的拼接方式进行单词重组。这里有一个细节需要注意,当遍历到最后一个单词后面还有空白内容时需要进行特殊处理,具体代码及注释如下。

class Solution {
public:
string reverseWords(string s) { //重点在于如何从字符串中提取单词
    int length = s.size();
    string temp;  //定义返回字符串
    for (int i = 0; i < length; ) //1层遍历字符串
    {
        string temp1 = " "; //设置空白字符,用于单词提取
        if (s[i] == ' ') i++; //遍历过程中遇到空白字符则跳过
        else {
            int counter = i;
            while (s[counter] != ' '&& counter<length) {//提取单词的过程
                temp1 += s[counter];
                counter++;
            }
            i = counter;
            while (counter < length) {  //当一个单词提取完成,查看后续是否还有单词需要提取
                if (isalpha(s[counter++])) {
                    i++;
                    break;
                }
            }
            if (counter == length) temp1.erase(temp1.begin()); //遍历结束,对temp1开头的空白进行特殊处理
            temp = temp1 + temp; //安题目要求拼接字符串
        }
    }
    return temp;
}
};

猜你喜欢

转载自www.cnblogs.com/hu-19941213/p/11043432.html
今日推荐