LeetCode 题解工作台
检查句子中的数字是否递增
句子是由若干 token 组成的一个列表, token 间用 单个 空格分隔,句子没有前导或尾随空格。每个 token 要么是一个由数字 0-9 组成的不含前导零的 正整数 ,要么是一个由小写英文字母组成的 单词 。 示例, "a puppy has 2 eyes 4 legs" 是一个由 7 个 …
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们可以将字符串 按空格分割成若干个单词。然后遍历每个单词,判断其是否为数字,若是数字,则将其转换为整数,与前一个数字比较,若不严格递增,返回 `false`,否则,将当前数字赋值给前一个数字,继续遍历。 遍历结束,说明字符串中的数字严格递增,返回 `true`。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
句子是由若干 token 组成的一个列表,token 间用 单个 空格分隔,句子没有前导或尾随空格。每个 token 要么是一个由数字 0-9 组成的不含前导零的 正整数 ,要么是一个由小写英文字母组成的 单词 。
- 示例,
"a puppy has 2 eyes 4 legs"是一个由 7 个 token 组成的句子:"2"和"4"是数字,其他像"puppy"这样的 tokens 属于单词。
给你一个表示句子的字符串 s ,你需要检查 s 中的 全部 数字是否从左到右严格递增(即,除了最后一个数字,s 中的 每个 数字都严格小于它 右侧 的数字)。
如果满足题目要求,返回 true ,否则,返回 false 。
示例 1:

输入:s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles" 输出:true 解释:句子中的数字是:1, 3, 4, 6, 12 。 这些数字是按从左到右严格递增的 1 < 3 < 4 < 6 < 12 。
示例 2:
输入:s = "hello world 5 x 5" 输出:false 解释:句子中的数字是:5, 5 。这些数字不是严格递增的。
示例 3:

输入:s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s" 输出:false 解释:s 中的数字是:7, 51, 50, 60 。这些数字不是严格递增的。
示例 4:
输入:s = "4 5 11 26" 输出:true 解释:s 中的数字是:4, 5, 11, 26 。 这些数字是按从左到右严格递增的:4 < 5 < 11 < 26 。
提示:
3 <= s.length <= 200s由小写英文字母、空格和数字0到9组成(包含0和9)s中数字 token 的数目在2和100之间(包含2和100)s中的 token 之间由单个空格分隔s中至少有 两个 数字s中的每个数字都是一个 小于100的 正 数,且不含前导零s不含前导或尾随空格
解题思路
方法一:模拟
我们可以将字符串 按空格分割成若干个单词。然后遍历每个单词,判断其是否为数字,若是数字,则将其转换为整数,与前一个数字比较,若不严格递增,返回 false,否则,将当前数字赋值给前一个数字,继续遍历。
遍历结束,说明字符串中的数字严格递增,返回 true。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def areNumbersAscending(self, s: str) -> bool:
pre = 0
for t in s.split():
if t[0].isdigit():
if (cur := int(t)) <= pre:
return False
pre = cur
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate efficiently handles string tokenization to extract numbers.
- question_mark
Evaluate how well the candidate compares numbers in sequence.
- question_mark
Observe the candidate's understanding of time and space complexity for string manipulation problems.
常见陷阱
外企场景- error
Overcomplicating the solution with unnecessary data structures.
- error
Misunderstanding the problem by considering non-numeric tokens or failing to account for the number order.
- error
Not handling edge cases, such as repeated numbers or numbers in incorrect order.
进阶变体
外企场景- arrow_right_alt
What if the sentence contains only numbers?
- arrow_right_alt
What if the sentence has words that don't contain numbers?
- arrow_right_alt
How would the solution change if numbers in the sentence had more than two digits?