【问题标题】:i stuck in leetcode problem 151. Reverse Words in a String我陷入了 leetcode 问题 151. 反转字符串中的单词
【发布时间】:2022-11-03 17:55:58
【问题描述】:

给定一个输入字符串 s,颠倒单词的顺序。 单词被定义为一系列非空格字符。 s 中的单词将至少用一个空格分隔。 以相反的顺序返回由单个空格连接的单词字符串。

class Solution {

public:

    string reverseWords(string s) {
        string ans;
        int i =0;
        int n = s.size();
        while(i<n)
        {
            while(i<n and s[i]==' ')
                i++;
            if(i>=n)
                break;
            int j =i+1;
            while(j<n and s[j]!=' ')
                j++;
            string word = s.substr(i,j-1);
            if(ans.size()==0)
                ans = word;
            else
                ans = word + " "+ ans;
            i = j+1;
            
        }
        return ans;
    }
};

预期输出——“blue is sky the” 我的输出-“蓝色是蓝天”

【问题讨论】:

  • 仅供参考:解决方案可以用std::istringstreamstd::stack&lt;std::string&gt; 写成4 行左右。无需检查空格。事实上,也许这就是问题所要寻找的答案,即堆栈数据结构的使用。
  • 另外,我不会将此作为答案发布,因为它看起来不像您的尝试(对我来说这非常令人费解,如果使用正确的数据结构,则解决方案的实际简单性),但是this is an example。现在,要弄清楚你的代码需要你调试代码,然后在问题中发布你的调试结果。

标签: java string stream time-complexity reverse


【解决方案1】:

您的代码中只有一个小错字。

线

        string word = s.substr(i,j-1);

应该

std::string word = s.substr(i, j - i);

所以你把 i 和 1 混为一谈了。

没什么大不了。

#include <string>
#include <iostream>

std::string reverseWords(std::string s) {
    std::string ans;
    int i = 0;
    int n = s.size();
    while (i < n)
    {
        while (i < n and s[i] == ' ')
            i++;
        if (i >= n)
            break;
        int j = i + 1;
        while (j < n and s[j] != ' ')
            j++;
        std::string word = s.substr(i, j - i);
        if (ans.size() == 0)
            ans = word;
        else
            ans = word + " " + ans;
        i = j + 1;

    }
    return ans;
}
int main() {
    std::cout << reverseWords("ab cd ef");
}

【讨论】:

    【解决方案2】:

    javascript解决方案:

    return str.split(' ').filter(s=>s!==' ').reverse().join(' ')
    

    【讨论】:

      猜你喜欢
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 2011-11-07
      • 1970-01-01
      相关资源
      最近更新 更多