LeetCode笔记:Weekly Contest 258(补发)

1. 题目一

给出题目一的试题链接如下:

1. 解题思路

这一题思路上就很简单,就是按照题目意思找到目标字符第一次出现的idx,然后反转该前缀序列。

2. 代码实现

给出python代码实现如下:

class Solution:
    def reversePrefix(self, word: str, ch: str) -> str:
        idx = word.find(ch)
        if idx == -1:
            return word
        return word[:idx+1][::-1] + word[idx+1:]

提交代码评测得到:耗时20ms,占用内存14.3MB。

2. 题目二

给出题目二的试题链接如下:

1. 解题思路

这一题思路也挺直接的,就是直接对每一个width与length的比值进行统计,然后对每一个比值,其可能的pair数目就是 n ( n − 1 ) 2 \frac{n(n-1)}{2} 2n(n1),对全部的比值进行求和即可得到最终的结果了。

2. 代码实现

给出python代码实现如下:

class Solution:
    def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
        cnt = defaultdict(int)
        for w, h in rectangles:
            cnt[w/h] += 1
        res = sum(x * (x-1) // 2 for x in cnt.values())
        return res

提交代码评测得到:耗时1580ms,占用内存71MB。

3. 题目三

给出题目三的试题链接如下:

1. 解题思路

这一题我的思路其实也有点暴力,就是遍历所有可能的分组,将原字符串分成两个子串,然后考察各自包含的最长的回文字符串长度,求出长度之后取出最大值即可。

这样的算法必然会产生大量的冗余,因为不同的分类可能得到完全相同的回文分类,不过整体来说,发现运行效率事实上还过去的……

2. 代码实现

给出python代码实现如下:

class Solution:
    def maxProduct(self, s: str) -> int:
        n = len(s)
        
        def divide_string(s, val):
            s1, s2 = "", ""
            idx = n-1
            while val != 0:
                if val % 2 == 1:
                    s1 = s[idx] + s1
                else:
                    s2 = s[idx] + s2
                idx -= 1
                val = val // 2
            s2 = s[:idx+1] + s2
            return s1, s2
        
        @lru_cache(None)
        def get_longest_palindrome(s):
            if len(s) <= 1:
                return len(s)
            idx = 0
            while True:
                nxt = s.find(s[0], idx+1)
                if nxt == -1:
                    break
                idx = nxt
            res = get_longest_palindrome(s[1:])
            if idx != 0:
                res = max(res, 2 + get_longest_palindrome(s[1:idx]))
            return res
        
        res = 1
        for val in range(1, 2**(n-1)+1):
            s1, s2 = divide_string(s, val)
            x = get_longest_palindrome(s1)
            y = get_longest_palindrome(s2)
            res = max(res, x*y)
        return res

提交代码评测得到:耗时389ms,占用内存17.5MB。

4. 题目四

给出题目四的试题链接如下:

这一题思路挺简单,用一个拓扑序列搜索即可,可惜超时,想了一周没有啥优化的思路,就放弃了,如果有兴趣的读者可以自行考虑一下,应该还是可解的,大概……

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值