LeetCode 题解工作台

统计星号

给你一个字符串 s ,每 两个 连续竖线 '|' 为 一对 。换言之,第一个和第二个 '|' 为一对,第三个和第四个 '|' 为一对,以此类推。 请你返回 不在 竖线对之间, s 中 '*' 的数目。 注意 ,每个竖线 '|' 都会 恰好 属于一个对。 示例 1: 输入: s = "l|*e*et|…

category

1

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们定义一个整型变量 ,表示遇到 `*` 时是否能计数,初始时 ,表示可以计数。 遍历字符串 ,如果遇到 `*`,则根据 的值决定是否计数,如果遇到 `|`,则 的值取反。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s ,每 两个 连续竖线 '|' 为 一对 。换言之,第一个和第二个 '|' 为一对,第三个和第四个 '|' 为一对,以此类推。

请你返回 不在 竖线对之间,s 中 '*' 的数目。

注意,每个竖线 '|' 都会 恰好 属于一个对。

 

示例 1:

输入:s = "l|*e*et|c**o|*de|"
输出:2
解释:不在竖线对之间的字符加粗加斜体后,得到字符串:"l|*e*et|c**o|*de|" 。
第一和第二条竖线 '|' 之间的字符不计入答案。
同时,第三条和第四条竖线 '|' 之间的字符也不计入答案。
不在竖线对之间总共有 2 个星号,所以我们返回 2 。

示例 2:

输入:s = "iamprogrammer"
输出:0
解释:在这个例子中,s 中没有星号。所以返回 0 。

示例 3:

输入:s = "yo|uar|e**|b|e***au|tifu|l"
输出:5
解释:需要考虑的字符加粗加斜体后:"yo|uar|e**|b|e***au|tifu|l" 。不在竖线对之间总共有 5 个星号。所以我们返回 5 。

 

提示:

  • 1 <= s.length <= 1000
  • s 只包含小写英文字母,竖线 '|' 和星号 '*' 。
  • s 包含 偶数 个竖线 '|'
lightbulb

解题思路

方法一:模拟

我们定义一个整型变量 ok\textit{ok},表示遇到 * 时是否能计数,初始时 ok=1\textit{ok}=1,表示可以计数。

遍历字符串 ss,如果遇到 *,则根据 ok\textit{ok} 的值决定是否计数,如果遇到 |,则 ok\textit{ok} 的值取反。

最后返回计数的结果。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
class Solution:
    def countAsterisks(self, s: str) -> int:
        ans, ok = 0, 1
        for c in s:
            if c == "*":
                ans += ok
            elif c == "|":
                ok ^= 1
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Checks whether the candidate can efficiently handle string traversal.

  • question_mark

    Assesses whether the candidate correctly identifies how to track the status of being inside or outside the '|' pair.

  • question_mark

    Evaluates the candidate's understanding of edge cases and proper exclusion of characters between '|' pairs.

warning

常见陷阱

外企场景
  • error

    Failing to handle the toggling of the inside/outside state when encountering '|' characters.

  • error

    Counting '*' characters within a '|' pair, even though they should be excluded.

  • error

    Not accounting for edge cases where there are no '*' characters or when they appear in odd patterns.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Variant with a larger string where performance optimization is required.

  • arrow_right_alt

    Variant where the string includes other symbols along with '*' and '|', introducing more complexity in exclusion logic.

  • arrow_right_alt

    Variant where the '|' characters are nested, requiring more careful tracking of their pairs.

help

常见问题

外企场景

统计星号题解:String-driven solution … | LeetCode #2315 简单