LeetCode101学习笔记-9.8
1 class Solution { 2 public: 3 int countSubstrings(string s) { 4 int ans=0; 5 for(int i=0;i<s.length();i++){ 6 ans+=extendSubstrings(s,i,i); 7 ans+=extendSubstrings(s,i,i+1); 8 } 9 return ans; 10 } 11 int extendSubstrings(string s,int l,int r){ 12 int cnt=0; 13 while(l>=0&&r<s.length()&&s[l]==s[r]){ 14 l--; 15 r++; 16 cnt++; 17 } 18 return cnt; 19 } 20 };
- LeetCode默认的链表表示方法如下:
* 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) {} * };
非递归解法
1 class Solution { 2 public: 3 ListNode* reverseList(ListNode* head) { 4 //非递归解法 5 ListNode *prev=nullptr,*next; 6 while(head){ 7 next=head->next; 8 head->next=prev; 9 prev=head; 10 head=next; 11 } 12 return prev; 13 } 14 };
递归解法
1 class Solution { 2 public: 3 ListNode* reverseList(ListNode* head,ListNode* prev=nullptr) { 4 //递归解法 5 if(!head)return prev; 6 ListNode* next=head->next; 7 head->next=prev; 8 return reverseList(next,head); 9 } 10 };
160. Intersection of Two Linked Lists
1 class Solution { 2 public: 3 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 4 ListNode *l1=headA,*l2=headB; 5 while(l1!=l2){ 6 //若二者不相交,两个指针完全走过两个链表后,将同时为空,继而退出循环。 7 l1=l1?l1->next:headB; 8 l2=l2?l2->next:headA; 9 } 10 return l1; 11 } 12 };
- 快慢指针找链表中点
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 bool isPalindrome(ListNode* head) { 14 if(!head || !head->next)return true; 15 ListNode *slow=head,*fast=head; 16 while(fast->next && fast->next->next){ 17 slow=slow->next; 18 fast=fast->next->next; 19 } 20 slow->next=reverseList(slow->next); 21 slow=slow->next; 22 while(slow){ 23 if(slow->val != head->val)return false; 24 slow=slow->next; 25 head=head->next; 26 } 27 return true; 28 } 29 ListNode* reverseList(ListNode* head) { 30 //非递归解法 31 ListNode *prev=nullptr,*next; 32 while(head){ 33 next=head->next; 34 head->next=prev; 35 prev=head; 36 head=next; 37 } 38 return prev; 39 } 40 };