C++ | Leetcode C++题解之第151题反转字符串中的单词

题目:

题解:

class Solution {
public:
    string reverseWords(string s) {
        int left = 0, right = s.size() - 1;
        // 去掉字符串开头的空白字符
        while (left <= right && s[left] == ' ') ++left;

        // 去掉字符串末尾的空白字符
        while (left <= right && s[right] == ' ') --right;

        deque<string> d;
        string word;

        while (left <= right) {
            char c = s[left];
            if (word.size() && c == ' ') {
                // 将单词 push 到队列的头部
                d.push_front(move(word));
                word = "";
            }
            else if (c != ' ') {
                word += c;
            }
            ++left;
        }
        d.push_front(move(word));
        
        string ans;
        while (!d.empty()) {
            ans += d.front();
            d.pop_front();
            if (!d.empty()) ans += ' ';
        }
        return ans;
    }
};

相关推荐

  1. [力扣题解] 151. 字符串单词

    2024-06-15 07:02:03       28 阅读
  2. 面试经典---151.字符串单词

    2024-06-15 07:02:03       54 阅读
  3. 力扣-151. 字符串单词

    2024-06-15 07:02:03       67 阅读
  4. 字符串单词(力扣151

    2024-06-15 07:02:03       37 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-15 07:02:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-15 07:02:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-15 07:02:03       82 阅读
  4. Python语言-面向对象

    2024-06-15 07:02:03       91 阅读

热门阅读

  1. Html_Css问答集(3)

    2024-06-15 07:02:03       26 阅读
  2. C++ 数据结构

    2024-06-15 07:02:03       33 阅读
  3. 设计模式之适配器模式

    2024-06-15 07:02:03       23 阅读
  4. GitHub每日最火火火项目(6.14)

    2024-06-15 07:02:03       32 阅读