Day11句子逆序

168 阅读2分钟

Day11句子逆序

题源

描述

将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”

所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符

数据范围:输入的字符串长度满足 1≤�≤1000 1≤n≤1000

注意本题有多组输入

输入描述:

输入一个英文语句,每个单词用空格隔开。保证输入只包含空格和字母。

输出描述:

得到逆序的句子

示例1

输入:

I am a boy

输出:

boy a am I

示例2

输入:

nowcoder

复制

输出:

nowcoder

具体思路

  • 法1:逆序肯定能用栈

    • 1.设置char栈,每当字符没有遇到空格的时候,字符进栈
    • 2.当遇到空格的时候,依次出栈且输出
    • 3.知道最后一个单词位置,最后单词单独跳出循环进行出栈输出

具体实现

#include <math.h>
#include <algorithm>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <stdlib.h>
#include <cstdlib>
#include <cstring>//#include "./include/list/sqlist.h"
​
using namespace std;
​
​
//Day11
//将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”
//所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符
//法1:非原地栈逆序法
/**
 * @description: 时间复杂度O(n*m)=O(n^2) 空间复杂度:O(n)
 * @param {string} s
 * @return {*}
 */
void ReverPhrase(string s){
    //从后往前遍历,然后直接遇到空格就放到新的string里面
    //设置栈
    stack<char> ans_stack;//字符栈
    string ans;
    int len_s = s.length();//字符串长度
    for(int i = len_s - 1; i >= 0; i--){
        if(s[i] != ' ') ans_stack.push(s[i]);//直接进栈
        else{
            //直接输出
            while(!ans_stack.empty()){
                char temp = ans_stack.top();//访问栈顶元素
                ans_stack.pop();//出栈
                printf("%c",temp);//打印
            }
            printf(" ");
        }
    }
    //最后一个单词输出,单独处理最后一个单词
    while(!ans_stack.empty()){
        char temp = ans_stack.top();
        ans_stack.pop();
        printf("%c",temp);
    }
    printf("\n");
    return;
}
​
​
//法2:递归法,理论上能用栈必能用递归算法int main(){
​
​
    // //day06
    // LinkList L;
    // int n;//输入数据数量
    // int index = 0;//输入的位置
    // ListNode* p;
    // while(scanf("%d",&n) != EOF){
    //     L = ListTailInsert(L,n);
    //     scanf("%d",&index);
    //     if(index == 0) std::cout << 0 << std::endl;
    //     else{
    //         p = FindKInListIII(L,index);
    //         if(p != NULL) printf("%d\n",p->data);
    //     }
    //     //PrintLinkedList(L);
    // }
    // int month_;
    // while(scanf("%d",&month_) != EOF){
    //     int ans = GetRabbitNums(month_);
    //     printf("%d\n",ans);
    // }
    //day8
    //string s;
    string s;
    while(cin >> s){
        //ReverseNum(n);
        ReverPhrase(s);
        //int len_ans = ans.length();
        //std::cout << ans << std::endl;
        //printf("\n");
    }
    // getline(cin, s);
    // ReverPhrase(s);
    //SplitStringIII(s);
    system("pause");
    return 0;
}

image.png

image.png

复杂度

法1:时间复杂度:O(n^2), 空间复杂度:O(n)

最好时间复杂度,当只有一个单词的时候,O(n)

最坏时间复杂度,当有很多空格的时候,需要不断遍历栈输出,时间复杂度为O(n*m)=O(n^2)

小结

思路是自己想到的,但是我看到别人的思路是,直接输入字符流,设置的是字符串栈,此类方法有待研究