双指针操作链表与字符串
LeetCode 83 删除排序链表中的重复元素 2023.12.28
- 题目链接
- labuladong讲解[链接]
ListNode* deleteDuplicates(ListNode* head) {/*暴力求解ListNode* cur = new ListNode();ListNode* prenode = cur;cur->next = head;cur = cur->next;while(cur && cur->next){if(cur->val == cur->next->val){if(cur->next->next)cur->next = cur->next->next;elsecur->next = NULL;}elsecur = cur->next;}return prenode->next;*///双指针求解//左右指针初始化均指向头节点,用右指针来遍历,左指针来存储ListNode* left = head;ListNode* right = head;//当右指针且右指针的next指针不为空时while(right && right->next){//如果右指针与右指针的next节点值相同,//则如果右指针next节点的next节点存在时,左指针的next节点=右指针next节点的next节点,然后继续遍历//否则如果右指针next节点的next节点不存在时,说明走到头了,则给左指针的next节点指向NULLif(right->val == right->next->val){if(right->next->next)left->next = right->next->next;elseleft->next = NULL;}//如果右指针与右指针的next节点值不相同,那么左右指针都继续遍历//实际上,左右指针都是保持同步的else{right = right->next;left = left->next;}}//返回头指针return head;
}
LeetCode 5 最长回文子串 2023.12.28
- 题目链接
- labuladong讲解[链接]
class Solution {public://求s字符串中的回文串,以l,r为中间两值的(奇数个字符时l=r为最中间的字符)string Palindrome(string s, int l, int r){//当左侧索引>=0,右侧索引<s.size()且s[l]=s[r]时//l--;r++;最终退出时说明s[l+1, r-1]为回文串while(l >= 0 && r < s.size() && s[l] == s[r]){l--;r++;}//返回s[l+1, r-1]回文串return s.substr(l+1, r-l-1);}string longestPalindrome(string s) {/*暴力求解string longstr;for(int i = 0; i < s.size(); i++){for(int j = i; j < s.size(); j++){int sym = 0;for(int k = i; k <= (i+j)/2; k++){if(s[k] != s[j-(k-i)]){sym = 1;break;} }if(sym == 0 && j-i+1>longstr.size())longstr = s.substr(i, j-i+1);}} return longstr;*///双指针求解//定义longstr变量存储遍历得到的最长回文串string longstr;//遍历每个以(i,i)、(i, i+1)为中心的s字符串的;将最长回文串存到longstr中for(int i = 0; i < s.size(); i++){string s1 = Palindrome(s, i, i);string s2 = Palindrome(s, i, i+1);longstr = longstr.size() < s1.size() ? s1 : longstr;longstr = longstr.size() < s2.size() ? s2 : longstr;}return longstr;}
};