一、字符串轮转
class Solution {
public:
bool isFlipedString(string s1, string s2) {
if(s1.size() != s2.size()) return false;
if(s1.size() == s2.size() & s1.size() == 0) return true;
string s3;
s3 = s2;
s3 += s2;
int n;
if(n = s3.find(s1) != string::npos)
return true;
else
return false;
}
};
总结:新增字符串为两个s2结合,如果s3中有s1子串就返回true;
二、移除链表重复节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeDuplicateNodes(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
//使用哈希表
unordered_set<int>uSet;
ListNode *rear = head->next;
ListNode *prev = head;
uSet.insert(head->val);
while(rear)
{
if(!uSet.count(rear->val))
{
uSet.insert(rear->val);
prev->next = rear;
prev = prev->next;
}
rear = rear->next;
}
prev->next = NULL;
return head;
}
};
总结:本题中由于要删除重复的节点,所以我们很容易想到C++中hash表,就对弈STL unordered_set, 然后遍历链表,使用前后指针。有发现重复的元素就一直向前移动。当没有出现重复的元素时,前驱指针先移动,最后在后继指针next置空,这样可以处理尾结点以及防止某处后面全为重复节点
三、返回链表倒数第K个节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int kthToLast(ListNode* head, int k) {
//双指针。先走K步,然后再让后驱跟前指针一起走。
if(head == NULL) return 0;
ListNode *prev = head;
while(k)
{
prev