zoukankan      html  css  js  c++  java
  • PAT乙级1009

    题目链接

    https://pintia.cn/problem-sets/994805260223102976/problems/994805316250615808

    题解一

    我的方法如下:

    1. 将这一行字符串格式看做:第一个单词( 单词)( 单词)( 单词)
    2. 利用循环输出所有( 单词)
    3. 输出第一个单词
    // PAT BasicLevel 1009
    // https://pintia.cn/problem-sets/994805260223102976/problems/994805314941992960
    
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        // 获取用户输入的一行
        string str;
        getline(cin,str);	// 可读取空格,遇到换行停止,并不读取换行
    
        // 将这一行字符串格式看做:第一个单词( 单词)( 单词)( 单词)
        // 从右边找空格然后一直输出( 单词)
        int indexOfSpace;
        while ((indexOfSpace = str.find_last_of(" ")) != str.npos) //length()和size()是一样的
        {
            cout << str.substr(indexOfSpace + 1, str.length()) << ' ';
            str=str.substr(0,indexOfSpace);
        } 
    
        // 输出第一个单词
        cout << str.substr(0,str.length());
    
        //system("pause");
        return 0;
    }
    

    题解二

    这个方法也挺不错的,我很喜欢。

    利用到了栈先进后出的特点,以及cin遇到空格和回车停止,不读取换行的特点。

    参考链接:https://www.cnblogs.com/cdp1591652208/p/7138046.html

    // PAT BasicLevel 1009
    // https://pintia.cn/problem-sets/994805260223102976/problems/994805314941992960
    
    #include <iostream>
    #include <string>
    #include <stack>
    
    using namespace std;
    
    int main()
    {
        // 保存所有单词
        stack<string> strs;
    
        // 保存一个单词 
        string str;
    
        // 读取所有单词
        while(cin>> str){
            strs.push(str);
            if(getchar()=='
    ')
                break;
        }
    
        // 输出所有单词
        cout << strs.top();
        strs.pop();
        while (!strs.empty()){
            cout << ' ' << strs.top();
            strs.pop();
        }
    
        //system("pause");
        return 0;
    }
    

    作者:@臭咸鱼

    转载请注明出处:https://chouxianyu.github.io

    欢迎讨论和交流!


  • 相关阅读:
    搭建Keil C51开发环境
    源码分析之Handler
    Android中的算法
    Android中的数据结构
    高级UI-UI绘制流程
    高级UI-Path和PathMeasure
    高级UI-画板Canvas
    高级UI-滤镜和颜色通道
    高级UI-高级渲染
    高级UI-画笔Paint
  • 原文地址:https://www.cnblogs.com/chouxianyu/p/11297910.html
Copyright © 2011-2022 走看看