【问题标题】:Reverse words in a sentence in c++ using stack使用堆栈在c ++中反转句子中的单词
【发布时间】:2018-03-09 18:01:57
【问题描述】:

输入

“天是蓝的”

预期输出

“蓝色是天空”

我的输出

“蓝色是天空”

我无法指出代码中的错误。

代码如下:

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s = "the sky is blue";
    reverse(s.begin(),s.end());
    stack<char> t;
    for(int i = 0;i < s.length();i++){
        if(s[i] != ' '){
            t.push(s[i]);
        }
        else{
            while(!t.empty()){
                cout << t.top();
                t.pop();
            }
            cout << " ";
        }
    }
    return 0;
}

【问题讨论】:

  • reverse 不会反转每个单词。如果你调试过你的代码,你应该已经看到了。
  • 我知道。反转后我正在使用堆栈打印出元素。
  • 这将反转每个单词...
  • Example of std::istringstream。无需检查空格。所以在发布任何答案并得到“我的老师或书没有教我这个,所以我不能使用它”之前,这是可以接受的吗?
  • 无关:注意#include &lt;bits/stdc++.h&gt; using namespace std; 组合。它可能导致一些几乎无法理解的错误。更多关于为什么在这里 stackoverflow.com/questions/31816095/… 和这里 stackoverflow.com/questions/1452721/… 。在您的全局命名空间中,您将拥有整个标准库。有很多潜在的地雷需要踩。

标签: c++ string loops stl stack


【解决方案1】:

您将“eht”推入堆栈,但您并没有开始弹出它,因为字符串的长度不允许您这样做,因为 for 循环停止执行。

在 for 循环之后弹出它,像这样:

#include <string>
#include <stack>
#include <algorithm>
#include <iostream>
using namespace std;
int main(){
  string s = "the sky is blue";
  reverse(s.begin(),s.end());
  stack<char> t;
  for(unsigned int i = 0;i < s.length();i++){
    if(s[i] != ' '){
      t.push(s[i]);
    }
    else {
      while(!t.empty()){
        cout << t.top();
        t.pop();
      }
      cout << " ";
   }
  }
  while(!t.empty()){
    cout << t.top();
    t.pop();
  }
}

输出:

蓝色是天空

【讨论】:

    【解决方案2】:

    C++ 程序使用 Stack 数据结构反转字符串中的单词。

    例如"my.name.is.vivek.mutha" 给出的输出为 "mutha.vivek.is.name.my"。

    #include<bits/stdc++.h>
    using namespace std;
    int main()
    {
        string s,s1;
        std::stack<std::string> st;
        int k=0;
        cin>>s;
        int l = s.length();
        vector<string> str;
        for(int i=0;i<l;i++)
        {
            if(s[i]=='.'){
                str.push_back(s1);
                str.push_back(".");
                s1="";
            }
            else
                s1.append(s,i,1);
        }
        str.push_back(s1);
        for(int i=0;i<str.size();i++)
            st.push(str[i]);
        while(!st.empty()){
            cout<<st.top();
            st.pop();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-22
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多