打印

【一天一道编程题】之Palindromic String

[复制链接]
721|3
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
michael_llh|  楼主 | 2017-1-1 20:48 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 michael_llh 于 2017-1-1 20:49 编辑

Palindromic String

You have been given a String SS. You need to find and print whether this string is a palindrome or not. If yes, print "YES" (without quotes), else print "NO" (without quotes).

Input Format
The first and only line of input contains the String SS. The String shall consist of lowercase English alphabets only.
Output Format
Print the required answer on a single line.

Constraints1≤|S|≤100
Note
String S consists of lowercase English Alphabets only.

SAMPLE INPUT

aba
SAMPLE OUTPUT

YES
comes from:

题意分析:

首先我们需要明白一点说什么是Palindromic 这个单词的意思,翻译过来就是回文,也就是说我们要判断这个字符串他是不是一个回文串。什么是回文串解释一下,回文串就是一个对称的字符串,比如说abaabba这两个字符串就是回文串。


好了。明白了题意,那么我们就可以开始思考如何解决这个问题了,其实比较简单的有一个方法就是利用C++中栈的数据结构,我们对字符串折半压栈,前半部分从头开始压栈,后半部分从尾开始压栈,利用两个栈来实现,最后弾栈对比就好啦,虽然这道题不需要用到栈就可以实现了,但是这也是一种方法,参考咯!

参考代码(C++
#include <iostream>
using namespace std;
#include <string>
#include <stack>

int main()
{
    string str;
    cin >> str;
    int half_length = str.size()/2;
    stack<char> s1;
    stack<char> s2;
    int flag=0;
    for(int i=0; i<half_length; i++){
        s1.push(str);
    }
    for(int i=0; i<half_length; i++){
        s2.push(str[str.size()-1-i]);
    }
    while(!s1.empty()){
        if(s1.top()!=s2.top()){
            flag = 1;
            break;
        }
        s1.pop();
        s2.pop();
    }
    if(flag){
        cout << "NO" << endl;
    }else{
        cout << "YES" << endl;
    }

}



另外一份参考代码:( C
#include <stdio.h>
#include <string.h>

int main()
{
    char string1[100];
    int i, length;
    int flag = 0;
    canf("%s", string1);

    length = strlen(string1);

    for(i=0; i < length ; i++)
    {
        if(string1 != string1[length-i-1])
        {
            flag = 1;
            break;
        }
    }

    if (flag)
    {
        printf("NO");
    }
    else
    {
        printf("YES");
    }
    return 0;
}






相关帖子

沙发
mlmbcsz| | 2017-1-3 08:33 | 只看该作者
学习了!

使用特权

评论回复
板凳
michael_llh|  楼主 | 2017-1-3 14:24 | 只看该作者

多多交流咯!

使用特权

评论回复
地板
michael_llh|  楼主 | 2017-1-3 14:24 | 只看该作者

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

22

主题

381

帖子

8

粉丝