zzuli-1858-单词翻转

1858: 单词翻转

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 254   Solved: 141

Submit Status Web Board

Description

小明终于等来了好朋友的来信,但打开来信就傻眼了,居然看不懂,原来好朋友把信中的每个单词都翻转了顺序,例如“Happy”在朋友的信里变成了“yppaH”。请你编写程序帮助小明还原来信内容吧。

Input

输入一个字符串,以回车结束。该字符串长度不超过100,包含多个单词,单词之间有一个或多个空格。

Output

输出一行,即单词翻转后的字符串,注意每对单词之间的空格数量保持不变。

Sample Input

yppaH wen raey

Sample Output

Happy new year


递归版
#include <bits/stdc++.h>

using namespace std;

char str[1100];
int dfs(int step , int len)
{
    if(str[step] == ' ' || step == len)
        return step;
    int idx = dfs(step+1 , len);
    printf("%d",str[step]);
    return idx;
}
int main()
{
    while(gets(str))
    {
        int len = strlen(str);
        for(int i=0; i<len; )
        {
            if(str[i] == ' ')
            {
                printf(" ");
                i += 1;
            }
            else
                i = dfs(i , len);
 
        }
	printf("\n");
    }
    return 0;
}






栈版 
#include <bits/stdc++.h>

using namespace std;

int main()
{
    char str[150];
    while(gets(str))
    {
        int len=strlen(str);
        for(int i=0;i<len;)
        {
            if(!isalpha(str[i]))
            {
                printf("%c",str[i++]);
                continue;
            }

            stack<char>  st;
            while(!st.empty())
                st.pop();

            while(isalpha(str[i]) && i<len)
            {
                st.push(str[i]);
                i++;
            }

            while(!st.empty())
            {
                printf("%c",st.top());
                st.pop();
            }
        }
    }
    return 0;
}





版权声明:本文为newproblems原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。