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;
}
}