【华为机试】13-字符串反转

版权声明:转载请注明出处!欢迎大家提出疑问或指正文章中的错误! https://blog.csdn.net/pyuxing/article/details/88861318

1- Description

写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。例如:

输入描述
输入N个字符
输出描述
输出该字符串反转后的字符串

示例1
输入:
abcd
输出:
dcba

2- Solution

  • 直接逆序输出即可
#include <iostream>
#include <string>

using namespace std;

int main(){
    string strin;
    while(cin >> strin){
        for(int i = strin.length() - 1; i >= 0; --i){
            cout << strin[i];
        }
    }
    return 0;
}
  • 利用栈的后进先出性质,可以很简洁的写出下面的代码
#include<iostream>
#include<stack>
using namespace std;
int main(void)
{
    char ch; 
    stack<char> ch_stack;
    while(cin>>ch)
    {
      ch_stack.push(ch); 
    }
    while(!ch_stack.empty())
    {
        cout<<ch_stack.top();//取栈顶元素,也就是最后输入的字符
        ch_stack.pop();//输出!
    }
    return 0;
}

欢迎关注公众号:CodeLab

猜你喜欢

转载自blog.csdn.net/pyuxing/article/details/88861318
今日推荐