Easy-题目54:234. Palindrome Linked List
来源:互联网 发布:弹弹安卓版吉他软件 编辑:程序博客网 时间:2024/06/05 19:05
题目原文:
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
题目大意:
给一个单链表,判断它是不是回文的。
你能实现O(n)时间复杂度和O(1)空间复杂度吗?
题目分析:
如果用O(1)空间复杂度的话,可以求出链表的中点,然后翻转前半个链表再比较两个“半链表”是否相同。但是,我觉得代码太麻烦,就改用O(n)的空间复杂度了,这样的算法很简单:把链表转换成线性表,因为是随机存储的很容易判断是否是回文。
源码:(language:cpp)
class Solution {public: bool isPalindrome(ListNode* head) { int length=0; for(ListNode* p=head;p;p=p->next,length++);//length is the length of linklist int* array=new int[length]; int i=0; for(ListNode* p=head;p;p=p->next) array[i++]=p->val; return isPalindromeArray(array,length); } bool isPalindromeArray(int* array,int length) { if(length==0||length==1) return true; else if(*array!=*(array+length-1)) return false; else return isPalindromeArray(array+1,length-2); }};
成绩:
28ms,beats 9.66%,众数28ms,58.57%
0 0
- Easy-题目54:234. Palindrome Linked List
- 234. Palindrome Linked List(Linked List-Easy)
- 234. Palindrome Linked List (Easy)
- 234. Palindrome Linked List [easy] (Python)
- Leetcode 234. Palindrome Linked List (Easy) (cpp)
- LeetCode-Easy部分标签为LinkedList 234. Palindrome Linked List
- 【LeetCode】234.Palindrome Linked List(Easy)解题报告
- [Leetcode 234, Easy] Palindrome Linked List
- 【Leetcode-Easy-234】Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 3. Longest Substring Without Repeating Characters
- CSS的继承性,特殊性和层叠性
- SDNU1332 矩阵交换
- Easy-题目53:257. Binary Tree Paths
- 递归
- Easy-题目54:234. Palindrome Linked List
- 虚表解析以及构造函数为什么不能是虚函数
- JAVA学习笔记整理四(异常处理)
- java int 与byte互转(转)
- 点击元素使其在毫秒内从不透明变为透明
- hdu 3879(最小割模型求解最大权闭合图)
- 抽象
- Easy-题目55:67. Add Binary
- 整理有关javaScript的知识3