| Total Complexity | 14 |
| Total Lines | 62 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 9 | class PalindromeLinkedList |
||
| 10 | { |
||
| 11 | public static function isPalindrome(ListNode $head): bool |
||
| 12 | { |
||
| 13 | $fast = $head; |
||
| 14 | $slow = $head; |
||
| 15 | while ($fast && $fast->next) { |
||
| 16 | $fast = $fast->next->next; |
||
| 17 | $slow = $slow->next; |
||
| 18 | } |
||
| 19 | if ($fast) { |
||
| 20 | $slow = $slow->next; |
||
| 21 | } |
||
| 22 | $fast = $head; |
||
| 23 | $slow = self::helper($slow); |
||
|
|
|||
| 24 | while ($slow) { |
||
| 25 | if ($fast->val !== $slow->val) { |
||
| 26 | return false; |
||
| 27 | } |
||
| 28 | $fast = $fast->next; |
||
| 29 | $slow = $slow->next; |
||
| 30 | } |
||
| 31 | |||
| 32 | return true; |
||
| 33 | } |
||
| 34 | |||
| 35 | /** |
||
| 36 | * Note: Time Limit Exceeded. |
||
| 37 | * |
||
| 38 | * @param \leetcode\util\ListNode $head |
||
| 39 | * |
||
| 40 | * @return bool |
||
| 41 | */ |
||
| 42 | public static function isPalindrome2(ListNode $head): bool |
||
| 43 | { |
||
| 44 | $node = $head; |
||
| 45 | $queue = []; |
||
| 46 | while ($node) { |
||
| 47 | array_push($queue, $node); |
||
| 48 | $node = $node->next; |
||
| 49 | } |
||
| 50 | while (count($queue) >= 2) { |
||
| 51 | [$p, $q] = [array_shift($queue), array_pop($queue)]; |
||
| 52 | if ($p && $q && $p->val != $q->val) { |
||
| 53 | return false; |
||
| 54 | } |
||
| 55 | } |
||
| 56 | |||
| 57 | return true; |
||
| 58 | } |
||
| 59 | |||
| 60 | private static function helper(ListNode $head): ?ListNode |
||
| 71 | } |
||
| 72 | } |
||
| 73 |