1、编写程序从命令行参数中读入一个字符串检查该字符串是否为回文串回文串的特点是顺序读和倒序读都是一样的jAVA详细注释
public class Palindrome {
public static void main(String[] args) {
// 从命令行参数中读入一个字符串
String str = args[0];
// 检查该字符串是否为回文串
if (isPalindrome(str)) {
System.out.println(str + " is a palindrome");
} else {
System.out.println(str + " is not a palindrome");
}
}
/**
* 判断一个字符串是否为回文串
* @param str 待判断的字符串
* @return true表示是回文串,false表示不是回文串
*/
public static boolean isPalindrome(String str) {
// 将字符串转换成字符数组
char[] chars = str.toCharArray();
// 定义左右两个指针,分别从字符串的两端开始遍历
int left = 0;
int right = chars.length - 1;
// 遍历字符数组,比较左右两个指针指向的字符是否相等
while (left < right) {
if (chars[left] != chars[right]) {
return false;
}
left++;
right--;
}
return true;
}
}
代码解释:
-
main方法中从命令行参数中读入一个字符串,并调用isPalindrome方法判断该字符串是否为回文串。 -
isPalindrome方法接收一个字符串参数,将字符串转换成字符数组,并定义左右两个指针,分别从字符串的两端开始遍历。 -
在遍历过程中,比较左右两个指针指向的字符是否相等,如果不相等,则该字符串不是回文串,返回
false。 -
如果左右两个指针指向的字符都相等,则继续遍历,直到左右两个指针相遇或者交叉,说明该字符串是回文串,返回
true。
原文地址: https://www.cveoy.top/t/topic/bif2 著作权归作者所有。请勿转载和采集!