647. Palindromic Substrings

 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) {}
 * };

 

206. Reverse Linked List

非递归解法

 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 };