-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path[E].[J].234.PalindromeLinkedList
42 lines (40 loc) · 1.14 KB
/
[E].[J].234.PalindromeLinkedList
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
/* Using String */
ListNode current = head;
StringBuilder s = new StringBuilder();
while (current != null){
s.append(current.val);
current = current.next;
}
String s1 = s.toString();
String s2 = s.reverse().toString();
if (s1.compareTo(s2) == 0){
return true;
} else return false;
/* Using HashMap */
ListNode current = head;
HashMap<Integer, Integer> hashMap = new HashMap<>();
int i = 1;
while (current != null){
hashMap.put(i++, current.val);
current = current.next;
}
for (int j = 1; j < i; j++) {
if (!Objects.equals(hashMap.get(j), hashMap.get(i - j))){
return false;
}
}
return true;
}
}