华为OD机试——单词倒序

题目描述

image

分析

  这里观察到对于每一个单词而言,都是倒转的,可以考虑使用栈后进先出的特性进行逆转。
  定义一个栈和一个存储输出答案的字符串,从前往后遍历字符串,当遇到普通单词时加入到栈中,遇到标点符号或空格时全部出栈,之后再将该字符加入到栈中,遍历完成后,记得再将栈中的内容出栈添加到字符串后面,最后再将答案输出即可。

代码

    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <stack>
    
    using namespace std;
    
    int main()
    {
    	string s, ans;
    	stack<char> st;
    	getline( cin, s );
    	int n = s.size();
    	for( int i=0; i<n; ++i )
    		if( s[i] == '.' || s[i] == '?' || s[i] == ',' || s[i] == ' ' )
    		{
    			while( !st.empty() ) 
    			{
    				ans += st.top();
    				st.pop();
    			}
    			ans += s[i];
    		}else
    		{
    			st.push( s[i] );
    		}
    	while( !st.empty() ) 
    	{
    		ans += st.top();
    		st.pop();
    	}
    	cout << ans << '\n';
    	return 0;
    }
posted @   平安顺遂233  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示