Topic 1:删除公共字符

本身没有什么难度,暴力解法的思路也很容易想出
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1, str2;
getline(cin , str1);
getline(cin , str2);
for(const auto& c : str1)
{
if(str2.find(c) == string::npos)
{
cout << c;
}
}
return 0;
}
像这种思路主要就考察STL和string容器的几个基本函数知识点——空格的获取不能直接cin >>,会截断, 要用getline;知道find和npos,npos取得size_t的最大值,还有审题,因为这里直接要求输出,所以甚至不需要用一个额外string来储存,直接输出即可,进一步节省。
但是还可以哈希的思路来扩展改善一下
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1, str2;
getline(cin, str1); getline(cin, str2);
bool hash[256] = {false}; // 仅需 256,char的ASCII只有255,也不用额外开哈希容器,用bool数组就行
for (char c : str2) hash[c] = true;
for (char c : str1) if (!hash[c]) cout << c;
return 0;
}
Topic 2:

用双指针法,让PA从A头开始走,走完就从B的头继续走,PB从B头走,走完就从A的头继续走,此时,如果两个单链表有公共节点,因为路程速度一样,那么PA走的总距离可以写作:PA = x + z + y + z,同理,PB = y + z + x + z; 把前面三个xyz约掉,最后一定会在公共节点相遇,所以在循环中,我们比较两个指针的地址是否相同,如果相同,那么该节点就是公共节点,而两个指针如果走到结尾,为空,都没有发现相同的地址,那就证明没有公共节点。


/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2)
{
ListNode* PA = pHead1;
ListNode* PB = pHead2;
bool otherA = false;
bool otherB = false;
while(PA != nullptr && PB != nullptr)
{
if(PA == PB)
{
return PA;
}
PA = PA->next;
PB = PB->next;
if(PA == nullptr && otherA == false)
{
PA = pHead2;
otherA = true;
}
if(PB == nullptr && otherB == false)
{
PB = pHead1;
otherB = true;
}
}
return nullptr;
}
};
优化优化
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
ListNode* PA = pHead1;
ListNode* PB = pHead2;
while (PA != PB) {
PA = (PA == nullptr) ? pHead2 : PA->next;
PB = (PB == nullptr) ? pHead1 : PB->next;
}
return PA;
}
};
很好
Topic 3:mari和shiny

本身是一个DP问题,和leetcode115. 不同的子序列一个解法
优化后
#include <iostream>
#include <vector>
using namespace std;
int main()
{
long long s = 0, h = 0, y = 0;
int n;
string str;
cin >> n >> str;
for(int i = 0;i < n;i ++)
{
char ch = str[i];
if(ch == 's') s ++;
else if(ch == 'h') h += s;
else if(ch == 'y') y += h;
}
cout << y << endl;
return 0;
}
之后有时间再来二刷复习
48天强训:算法题解题思路分享
4671

被折叠的 条评论
为什么被折叠?



