LeetCode Biweekly Contest No. 81 (1/4)

该博客介绍了如何解决一个字符串处理问题,即在给定的字符串中,统计每一对垂直条' '| '之间的'*'数量,但不包括特定分组的'*'。解题思路涉及遍历字符串,通过跟踪' '| '的奇偶性来确定哪些'*'应该被计数。给出的Python代码实现了一个高效解决方案,时间复杂度为O(N),空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem 1. 2315. Count Asterisks
 

题目描述:

You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth.

Return the number of '*' in sexcluding the '*' between each pair of '|'.

Note that each '|' will belong to exactly one pair.

Example 1:

Input: s = "l|*e*et|c**o|*de|"
Output: 2
Explanation: The considered characters are underlined: "l|*e*et|c**o|*de|".
The characters between the first and second '|' are excluded from the answer.
Also, the characters between the third and fourth '|' are excluded from the answer.
There are 2 asterisks considered. Therefore, we return 2.

Example 2:

Input: s = "iamprogrammer"
Output: 0
Explanation: In this example, there are no asterisks in s. Therefore, we return 0.

Example 3:

Input: s = "yo|uar|e**|b|e***au|tifu|l"
Output: 5
Explanation: The considered characters are underlined: "yo|uar|e**|b|e***au|tifu|l". There are 5 asterisks considered. Therefore, we return 5.

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters, vertical bars '|', and asterisks '*'.
  • s contains an even number of vertical bars '|'.

解题思路:

问题是统计两个"|"(称为"|"对儿)之间的"*"的个数,并且排除掉一部分"|"对儿

排除掉的"|"对儿的特征是:

第1、2个,第3、4个,第5,6个……

基于这样的特征,我们用一个bool变量b存储当前"|"的个数的奇偶性,当为偶数个时,对"*"进行计数。每次遇到新的"|"时,变更b的状态,于是:

class Solution:
    def countAsterisks(self, s: str) -> int:
        ret = 0
        b = False
        for i, t in enumerate(s):
            if t == '|':
                b = not b
            if not b and t == '*':
                ret += 1
        return ret

时间复杂度:O(N)

额外空间复杂度:O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值