-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPalindrome.java
61 lines (55 loc) Β· 1.36 KB
/
Palindrome.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package day5;
import java.util.Scanner;
public class Palindrome {
private static final Scanner scanner = new Scanner(System.in);
/*
time complexity: O(n)
space complexity: O(n)
*/
public static void main(String[] args) {
int length = scanner.nextInt();
int[] array = getArray(length);
System.out.println(isPalindrome(array) ? "palindrome" : "not palindrome");
}
/*
mom
hah
a
aaa
bat
{1, 2, 2, 1} true
{1} true
{} true
{1, 2, 3, 2, 1} true
{-100, -100} true
{1, 2, 3} false
{1, 2} false
{1, -100, 4} false
{1, x, 1} true
{1, 10, 10, 1}
{1, 2, 3, 1} -->
*/
/*
time complexity: O(n)
space complexity: O(1)
*/
private static boolean isPalindrome(int[] array) {
for (int i = 0 ; i < array.length / 2 ; i++) {
if (array[i] != array[array.length - i - 1]) {
return false;
}
}
return true;
}
/*
time complexity: O(n)
space complexity: O(n)
*/
private static int[] getArray(int length) {
int[] array = new int[length];
for (int index = 0 ; index < array.length ; index++) {
array[index] = scanner.nextInt();
}
return array;
}
}