-
Notifications
You must be signed in to change notification settings - Fork 3
/
_401_Palindromes.java
84 lines (70 loc) · 2.45 KB
/
_401_Palindromes.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package io.github.tahanima.uva;
import java.util.HashMap;
import java.util.Scanner;
/**
* @author tahanima
*/
public class _401_Palindromes {
public static boolean isPalindrome(String word) {
int n = word.length();
for (int i = 0, j = n - 1; i < j; i++, j--) {
if (word.charAt(i) != word.charAt(j))
return false;
}
return true;
}
public static boolean isMirroredString(String word, HashMap<Character, Character> map) {
int n = word.length();
for (int i = 0, j = n - 1; i <= j; i++, j--) {
if (map.containsKey(word.charAt(i))) {
char a = map.get(word.charAt(i));
if (a != word.charAt(j))
return false;
} else if (map.containsKey(word.charAt(j))) {
char a = map.get(word.charAt(j));
if (a != word.charAt(i))
return false;
} else {
return false;
}
}
return true;
}
public static void main(String[] args) {
HashMap<Character, Character> map = new HashMap<>();
map.put('A', 'A');
map.put('E', '3');
map.put('H', 'H');
map.put('I', 'I');
map.put('J', 'L');
map.put('M', 'M');
map.put('O', 'O');
map.put('S', '2');
map.put('T', 'T');
map.put('U', 'U');
map.put('V', 'V');
map.put('W', 'W');
map.put('X', 'X');
map.put('Y', 'Y');
map.put('Z', '5');
map.put('1', '1');
map.put('8', '8');
Scanner scanner = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNext()) {
String word = scanner.next();
boolean isPali = isPalindrome(word);
boolean isMirroredStr = isMirroredString(word, map);
if (isPali && isMirroredStr) {
stringBuilder.append(String.format("%s -- is a mirrored palindrome.%n%n", word));
} else if (isPali) {
stringBuilder.append(String.format("%s -- is a regular palindrome.%n%n", word));
} else if (isMirroredStr) {
stringBuilder.append(String.format("%s -- is a mirrored string.%n%n", word));
} else {
stringBuilder.append(String.format("%s -- is not a palindrome.%n%n", word));
}
}
System.out.print(stringBuilder);
}
}