此提示单链表判断回文,我本来的思路是逆转单链表前半截,再跑一次,应该能满足时间复杂度 (O(n)) 和空间复杂度 (O(1)),但是不知道为啥老判我超时。
看了 discuss 和 hint,其实简单递归一下就可以了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| class Solution {
public:
ListNode * temp;
bool isPalindrome(ListNode* head) {
temp = head;
return check(head);
}
bool check(ListNode * node) {
if (node == NULL) return true;
bool flag = check(node->next) && (node->val == temp->val);
temp = temp->next;
return flag;
}
};
|