Coding Practice,48天强训(12)

48天强训:算法题解题思路分享
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;
}

之后有时间再来二刷复习

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值