Problem Description
A sentence is a string of single-space separated words where each word can include digits, lowercase letters, and the dollar sign. A word represents a price if it starts with a dollar sign followed by a sequence of digits. Given a sentence and a discount percentage, the task is to apply the discount to every valid price, update it to exactly two decimal places, and return the modified sentence.
Key Insights
- Identify words that start with '$' and contain only digits afterwards.
- Extract the numeric value from valid price words.
- Apply the discount using the formula: discounted_price = price * (100 - discount) / 100.
- Format the discounted price to exactly two decimal places.
- Reconstruct the sentence with the updated prices.
Space and Time Complexity
Time Complexity: O(n), where n is the number of characters in the sentence. Space Complexity: O(n), as we store the split words and the final sentence.
Solution
The solution involves splitting the sentence into words, then checking each word to see if it represents a valid price. For a valid price (i.e., it begins with '$' and the remainder consists solely of digits), extract the number, apply the discount, and format the result with exactly two decimal places. Finally, reassemble the words into the final sentence. This approach uses simple string manipulation combined with arithmetic operations and formatting functions.