728x90
반응형
https://leetcode.com/problems/palindrome-linked-list/description/
문제
문제 분석
- Linked List의 값들을 다른 자료형에 옮겨서 양 끝을 하나씩 검사하는 방식으로 palindrome을 검사할 수 있을 것입니다. 양 끝에서만 접근이 이루어지기 때문에 Deque를 쓰는 것이 가장 효율적이라고 생각했습니다.
- Runner 기법을 사용하여 구현한다면 모든 ListNode를 다른 자료형에 넣지 않고도 검사할 수 있을 것 입니다. 절반까지만 딱 읽어드리면서 그 절반을 reverse한 Linked List를 만들고, 이걸 남은 절반과 비교하면 됩니다.
풀이 1 (Deque)
/**
* 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 {
private:
std::deque<int> deq;
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) {
return true;
}
ListNode* current = head;
while(current != nullptr){
deq.push_back(current->val);
current = current->next;
}
while(deq.size() > 1){
if (deq.front() != deq.back()){
return false;
}
deq.pop_front();
deq.pop_back();
}
return true;
}
};
풀이 2(Runner)
/**
* 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) {
if (!head || !head->next) {
return true;
}
ListNode* fast = head;
ListNode* slow = head;
ListNode* prev = nullptr;
while(fast && fast->next){
fast = fast->next->next;
ListNode* next_slow = slow->next;
slow->next = prev;
prev = slow;
slow = next_slow;
}
if(fast){
slow = slow->next;
}
while(prev && slow){
if(prev->val != slow->val){
return false;
}
prev = prev->next;
slow = slow->next;
}
return true;
}
};
728x90
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] C++ 206. Reverse Linked List (0) | 2024.08.16 |
---|---|
[LeetCode] C++ 21. Merge Two Sorted Lists (0) | 2024.08.16 |
[LeetCode] C++ 121. Best Time to Buy and Sell Stock (0) | 2024.08.16 |
[LeetCode] C++ 238. Product of Array Except Self (0) | 2024.08.16 |
[LeetCode] C++ 561. Array Partition I (0) | 2024.08.15 |