java —— 回文串字符

java —— 回文串字符

题目详情

“xyzyx”是一个回文字符串,所谓回文字符串就是指正读反读均相同的字符序列,
如“席主席”、“记书记”、“aha”和“ahaha”均是回文,但“ahah”不是回文。
输入一行字符(仅包含小写英文字母a~z)请判断这行字符串是否为回文。

输入格式:

只有一行,仅包含小写英文字母a~z的字符串,长度小于等于100。

输出格式:

只有一行,如果是回文请输出YES,不是回文则输出NO,请注意大小写。

样例1:

输入:
ahah

输出:
NO

样例2:

输入:
ahaha

输出:
YES

代码如下:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char[] str = sc.next().toCharArray(); // 输入一个字符串并转换为字符数组
        if (str.length % 2 == 0){ // 判断字符数组的长度
            if (Judge(str, str.length / 2) == 1){
                System.out.println("YES");
            }else System.out.println("NO");
        }else{
            if (Judge(str, (str.length + 1) / 2) == 1){
                System.out.println("YES");
            }else System.out.println("NO");
        }
    }

    public static int Judge(char[] a, int n) { // 判断是否是回文字符串
        int i = 0;
        while (i < n) {
            if (a[i] == a[a.length - i - 1])
                i++;
            else return 0;
        }
        return 1;
    }
}

代码二:(提供者Julpsztx)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char[] str = sc.next().toCharArray(); // 输入一个字符串并转换为字符数组
        System.out.println(Judge(str, str.length / 2) ? "YES" : "NO");
    }

    public static boolean Judge(char[] a, int n) { // 判断是否是回文字符串
        int i = 0;
        while (i < n) {
            if (a[i] == a[a.length - i-1])
                i++;
            else return false;
        }
        return true;
    }
}

END

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值