For a given array A[] composed of positive integers, if the arrangement of the numbers after A is reversed is exactly the same as that of A, then the array A is a palindrome. For example [1, 2, 3, 2, 1] is a palindrome, but [1, 2, 3, 4] is not a palindrome.
To determine whether an array is a palindrome, there are usually the following implementation ideas:
- Two-way traversal from end to end to determine whether the elements of the array are the same;
- Reverse the entire array, and judge whether the reversed array elements are the same as the original array elements one by one;
Example 1 - end-to-end bidirectional traversal :
private static boolean isPalindrome(int[] array) {
for (int start = 0, end = array.length - 1; start < end; start++, end--) {
if (array[start] != array[end]) {
return false;
}
}
return true;
}
Or use a while loop to achieve
private static boolean isPalindrome(int[] array) {
int start = 0;
int end = array.length - 1;
while (start < end) {
if (array[start] != array[end]) {
return false;
}
start++;
end--;
}
return true;
}
Example 2 - Reverse array :
private static boolean isPalindrome(int[] array) {
int[] reversedArray = new int[array.length];
for (int i = array.length - 1; i >= 0; i--) {
reversedArray[array.length - 1 - i] = array[i];
}
for (int i = 0; i < array.length; i++) {
if (array[i] != reversedArray[i]) {
return false;
}
}
return true;
}
Test verification
public static void main(String[] args) {
System.out.println(isPalindrome(new int[]{1, 2, 3, 2, 1}));
System.out.println(isPalindrome(new int[]{1, 2, 3, 4}));
}
The output is as follows:
true
false
For more knowledge points related to Java interviews, you can pay attention to the [Java Interview Manual] applet, which involves Java foundation, multithreading, JVM, Spring, Spring Boot, Spring Cloud, Mybatis, Redis, database, data structure and algorithm.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。