三種迴文判斷程式碼
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a string: ");
String s = input.nextLine();
System.out.println(s + (isPalindrome(s) ? " is" : " is not") + " a Palindrome");
}
public static boolean isPalindrome(String s){
// The index of the first character in the string
int low = 0;
// The index of the last character in the string
int high = s.length() - 1;
boolean isPalindrome = true;
while (low < high) {
if (s.charAt(low) != s.charAt(high)) {
isPalindrome = false;
break;
}
low++;
high--;
}
return isPalindrome;
}
}
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a string: ");
String s = input.nextLine();
System.out.println(s + (isPalindrome(s) ? " is" : " is not") + " a Palindrome");
}
public static boolean isPalindrome(String s) {
if (s.length() <= 1) {
return true;
} else if (s.charAt(0) != s.charAt(s.length() - 1)) {
return false;
} else {
return isPalindrome(s.substring(1, s.length() - 1));
}
}
}
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a string: ");
String s = input.nextLine();
System.out.println(s + (isPalindrome(s) ? " is" : " is not") + " a Palindrome");
}
public static boolean isPalindrome(String s) {
return isPalindrome(s, 0, s.length() - 1);
}
// overloading
private static boolean isPalindrome(String s, int low, int high) {
if (high <= low) {
return true;
} else if (s.charAt(low) != s.charAt(high)) {
return false;
} else {
return isPalindrome(s, low + 1, high - 1);
}
}
}