LeetCode 题解工作台

检查是否所有 A 都在 B 之前

给你一个 仅 由字符 'a' 和 'b' 组成的字符串 s 。如果字符串中 每个 'a' 都出现在 每个 'b' 之前,返回 true ;否则,返回 false 。 示例 1: 输入: s = "aaabbb" 输出: true 解释: 'a' 位于下标 0、1 和 2 ;而 'b' 位于下标 3、…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

根据题意,字符串 仅由字符 `a`, `b` 组成。 要使得所有 `a` 都在 `b` 之前出现,需要满足 `b` 之后不会出现 `a`,也就是说,字符串 "ba" 不是字符串 的子串,条件才能成立。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 由字符 'a''b' 组成的字符串  s 。如果字符串中 每个 'a' 都出现在 每个 'b' 之前,返回 true ;否则,返回 false

 

示例 1:

输入:s = "aaabbb"
输出:true
解释:
'a' 位于下标 0、1 和 2 ;而 'b' 位于下标 3、4 和 5 。
因此,每个 'a' 都出现在每个 'b' 之前,所以返回 true 。

示例 2:

输入:s = "abab"
输出:false
解释:
存在一个 'a' 位于下标 2 ,而一个 'b' 位于下标 1 。
因此,不能满足每个 'a' 都出现在每个 'b' 之前,所以返回 false 。

示例 3:

输入:s = "bbb"
输出:true
解释:
不存在 'a' ,因此可以视作每个 'a' 都出现在每个 'b' 之前,所以返回 true 。

 

提示:

  • 1 <= s.length <= 100
  • s[i]'a''b'
lightbulb

解题思路

方法一:脑筋急转弯

根据题意,字符串 ss 仅由字符 a, b 组成。

要使得所有 a 都在 b 之前出现,需要满足 b 之后不会出现 a,也就是说,字符串 "ba" 不是字符串 ss 的子串,条件才能成立。

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

1
2
3
4
class Solution:
    def checkString(self, s: str) -> bool:
        return "ba" not in s
speed

复杂度分析

指标
时间complexity is O(n) since the string is scanned once, and space complexity is O(1) because only a few variables are needed to track the state.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    They may hint at checking 'b' before 'a' as an opposite strategy.

  • question_mark

    Expect candidates to recognize linear scan suffices due to the two-character constraint.

  • question_mark

    Look for proper handling of edge cases like all 'a's or all 'b's.

warning

常见陷阱

外企场景
  • error

    Assuming characters other than 'a' and 'b' can appear.

  • error

    Failing to handle strings with no 'a's or no 'b's.

  • error

    Overcomplicating with extra data structures instead of a simple pass.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check if all 'b's appear after all 'c's in a similar character-constrained string.

  • arrow_right_alt

    Determine if a string of 'x' and 'y' follows a strict order like 'x' before 'y'.

  • arrow_right_alt

    Validate sequences where multiple character types must appear in defined order.

help

常见问题

外企场景

检查是否所有 A 都在 B 之前题解:String-driven solution … | LeetCode #2124 简单