一.介绍
程序使用两个变量,low和high,‘表示位于字符串s中开始和末尾的两个字符的位置。初始时,low为0,high为s.length()-1。如果位于这两个位置的字符匹配,则将low加1,high减1。这个过程一直继续到(low>=high),或者找到一个不匹配。
程序使用一个boolean变量isPalindrome来表示字符串s是否回文。初始时,该变量设置为true。当一个不匹配出现的时候,isPalindrome设置为false,循环由一个break语句结束。
二.代码
package com.zhuo.base.com.zhuo.base;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a String: ");
String s = input.nextLine();
//字符串中第一个字符的索引
int low = 0;
//字符串中最后一个字符的索引
int high = s.length() - 1;
boolean isPalindrome = true;
while (low < high) {
if (s.charAt(low) != s.charAt(high)) {
isPalindrome = false;
break;
}
low ++;
high --;
}
if (isPalindrome)
System.out.println(s + " is a palindrome");
else
System.out.println(s + " is not a palindrome");
}
}
三.结果显示
Enter a String: moon
moon is not a palindrome
Process finished with exit code 0
Enter a String: nonn
nonn is not a palindrome
Process finished with exit code 0