【Leetcode】234. 回文链表
目录
- 一、题目
- 二、思路
- 2.1 解题思路
- 2.2 代码尝试
- 2.3 疑难问题
- 2.4 AI复盘
- 三、解法
- 解法1,链表转数组
- 解法二
- 四、收获
- 4.1 心得
- 4.2 举一反三
一、题目
二、思路
2.1 解题思路
2.2 代码尝试
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
unordered_map<int,int> hash;
while(head){
if(hash[head->val]==0){
hash[head->val]++;
head=head->next;
}else{
hash[head->val]--;
head=head->next;
}
}
//查找哈希表中是否存在值为1的键
if(hash.empty()){
return true;
}else{
return false;
}
}
};
2.3 疑难问题
2.4 AI复盘
你使用 unordered_map 来记录每个值的出现次数,但这种方法无法判断链表是否是回文的。
回文链表的特点是正序和逆序的值序列相同,而你的代码只是统计了值的出现次数,无法反映顺序信息。
确实,这种哈希表只能记录出现次数,但是顺序信息不保留。
你的代码在最后检查 hash 是否为空,但这并不能判断链表是否是回文的。
三、解法
解法1,链表转数组
用数组存储链表值,然后判断数组是否回文,用双指针
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> vals;
while (head != nullptr) {
vals.emplace_back(head->val);
head = head->next;
}
for (int i = 0, j = (int)vals.size() - 1; i < j; ++i, --j) {
if (vals[i] != vals[j]) {
return false;
}
}
return true;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/palindrome-linked-list/solutions/457059/hui-wen-lian-biao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解法二
用递归优雅地反向遍历,然后同时有一个从左往右的节点,来进行双指针的判断
class Solution {
ListNode* frontPointer;
public:
bool recursivelyCheck(ListNode* currentNode) {
if (currentNode != nullptr) {
if (!recursivelyCheck(currentNode->next)) {
return false;
}
if (currentNode->val != frontPointer->val) {
return false;
}
frontPointer = frontPointer->next;
}
return true;
}
bool isPalindrome(ListNode* head) {
frontPointer = head;
return recursivelyCheck(head);
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/palindrome-linked-list/solutions/457059/hui-wen-lian-biao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
四、收获
4.1 心得
递归真的优雅
然后两种解法其核心都是双指针,一头一尾来进行判断,解决回文的问题
4.2 举一反三
回文的本质是双指针
现在刷着刷着,觉得实现代码并不重要了,因为现在AI工具就是能帮你实现,关键还是在于思路。所以要靠刷题来积累思路和想法。