LeetCode 题解工作台
价格减免
句子 是由若干个单词组成的字符串,单词之间用单个空格分隔,其中每个单词可以包含数字、小写字母、和美元符号 '$' 。如果单词的形式为美元符号后跟着一个非负实数,那么这个单词就表示一个 价格 。 例如 "$100" 、 "$23" 和 "$6" 表示价格,而 "100" 、 "$" 和 "$1e5 不…
1
题型
5
代码语言
3
相关题
当前训练重点
中等 · String-driven solution strategy
答案摘要
我们可以将句子按空格分割成单词数组,然后遍历单词数组,对于每个单词,如果其表示价格,则将其更新为减免折扣后的价格。最后将更新后的单词数组拼接成以空格分隔的字符串即可。 时间复杂度 ,空间复杂度 。其中 为字符串 `sentence` 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
句子 是由若干个单词组成的字符串,单词之间用单个空格分隔,其中每个单词可以包含数字、小写字母、和美元符号 '$' 。如果单词的形式为美元符号后跟着一个非负实数,那么这个单词就表示一个 价格 。
- 例如
"$100"、"$23"和"$6"表示价格,而"100"、"$"和"$1e5不是。
给你一个字符串 sentence 表示一个句子和一个整数 discount 。对于每个表示价格的单词,都在价格的基础上减免 discount% ,并 更新 该单词到句子中。所有更新后的价格应该表示为一个 恰好保留小数点后两位 的数字。
返回表示修改后句子的字符串。
注意:所有价格 最多 为 10 位数字。
示例 1:
输入:sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50 输出:"there are $0.50 $1.00 and 5$ candies in the shop" 解释: 表示价格的单词是 "$1" 和 "$2" 。 - "$1" 减免 50% 为 "$0.50" ,所以 "$1" 替换为 "$0.50" 。 - "$2" 减免 50% 为 "$1" ,所以 "$2" 替换为 "$1.00" 。
示例 2:
输入:sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100 输出:"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$" 解释: 任何价格减免 100% 都会得到 0 。 表示价格的单词分别是 "$3"、"$5"、"$6" 和 "$9"。 每个单词都替换为 "$0.00"。
提示:
1 <= sentence.length <= 105sentence由小写英文字母、数字、' '和'$'组成sentence不含前导和尾随空格sentence的所有单词都用单个空格分隔- 所有价格都是 正 整数且不含前导零
- 所有价格 最多 为
10位数字 0 <= discount <= 100
解题思路
方法一:模拟
我们可以将句子按空格分割成单词数组,然后遍历单词数组,对于每个单词,如果其表示价格,则将其更新为减免折扣后的价格。最后将更新后的单词数组拼接成以空格分隔的字符串即可。
时间复杂度 ,空间复杂度 。其中 为字符串 sentence 的长度。
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
ans = []
for w in sentence.split():
if w[0] == '$' and w[1:].isdigit():
w = f'${int(w[1:]) * (1 - discount / 100):.2f}'
ans.append(w)
return ' '.join(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate efficiently identify price words in a sentence?
- question_mark
Does the candidate apply the correct formatting to decimal numbers?
- question_mark
Does the candidate recognize edge cases such as 0% or 100% discounts?
常见陷阱
外企场景- error
Forgetting to handle the case where the discount is 0% or 100% correctly.
- error
Not ensuring that prices are formatted to two decimal places, even when the result is a round number.
- error
Misidentifying words that may contain a dollar sign but do not represent a price.
进阶变体
外企场景- arrow_right_alt
Implementing a solution that works for longer sentences with more words and prices.
- arrow_right_alt
Handling cases where there are no prices in the sentence.
- arrow_right_alt
Optimizing for larger inputs to handle edge cases like long strings efficiently.