最後のインデックスから最初のインデックスまでトラバースするだけで、文字または整数の配列を簡単に逆にすることができます。
int[] myArray = new int[10];//Array size is 10
//Traverse from last index= 9 to the first Index= 0
for(int i= myArray.length-1; i>= 0 ; --i){
System.out.print(myArray[i]);//here i is last index=10-1=9.
}
しかし、大文字と小文字を無視し、大文字と小文字を区別せずに、ユーザーが指定した文字列が回文であることを確認しようとします。
import java.util.Scanner;
public class Palindrome {
public void StringPalindrome(String original) {
String reverse = "";
for (int i = original.length() - 1; i >= 0; i--) {
reverse += original.charAt(i);
}
if (original.equals(reverse)) {
System.out.println("Entered string is palindrome \n" + "Original = " + original + "\n Reverse = " + reverse);
} else {
System.out.println("Entered string is not a palindrome.");
}
}
public void StringPalindromeIgnoreCase(String original) {
String reverse = "";
for (int i = original.length() - 1; i >= 0; i--) {
reverse += original.charAt(i);
}
if (original.equalsIgnoreCase(reverse)) {
System.out.println("Entered string is palindrome \n" + "Original = " + original + "\n Reverse = " + reverse);
} else {
System.out.println("Entered string is not a palindrome.");
}
}
public void reverseArrayInteger(int number[]) {
for (int i = number.length - 1; i >= 0; i--) {
System.out.print(number[i]);
}
System.out.println(" ");
}
public static void main(String[] args) {
Palindrome myPalindrom = new Palindrome();
testReverseIntegerArray(myPalindrom);
testStringPalindrome(myPalindrom);
testStringPaligrameIgnoreCase(myPalindrom);
}
public static void testReverseIntegerArray(Palindrome myPalindrom) {
int[] number = {1, 3, 5, 7, 8};
myPalindrom.reverseArrayInteger(number);
}
public static void testStringPalindrome(Palindrome myPalindrom) {
Scanner in = new Scanner(System.in);
String original;
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
myPalindrom.StringPalindrome(original);
}
public static void testStringPaligrameIgnoreCase(Palindrome myPalindrom) {
Scanner in = new Scanner(System.in);
String original;
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
myPalindrom.StringPalindromeIgnoreCase(original);
}
}
簡単な出力:
87531
Enter a string to check if it is a palindrome
MADAM
Entered string is palindrome
Original = MADAM
Reverse = MADAM
Enter a string to check if it is a palindrome
MaDAm
Entered string is palindrome
Original = MaDAm
Reverse = mADaM