Link: https://leetcode.com/problems/apply-discount-to-prices/
Solution:
Topics: subarray
Intuition
The code kind of speaks for itself in this case. Just split the string by spaces and check if the first character is $
, if so then check if everything following $
is a digit, if so apply the discount.
The discount calculation must be converted into the appropriate multiplication. For example, a discount of 80% is a multiplication by 0.2. Therefore the formula is as follows:
multiplier = (100 - discount)/100
Implementation
Visual
Review 1
Most of these parsing problems require splitting. Split by spaces, if the start is $
and the rest is a digit, apply the discount. Join back into a sentence at the end.