Apply Discount to Prices
Problem
A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign.
- For example,
"$100","$23", and"$6"represent prices while"100","$", and"$1e5"do not.
You are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of
discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.
Return a string representing the modified sentence.
Note that all prices will contain at most 10 digits.
Examples
Example 1
Input: sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50
Output: "there are $0.50 $1.00 and 5$ candies in the shop"
Explanation:
The words which represent prices are "$1" and "$2".
- A 50% discount on "$1" yields "$0.50", so "$1" is replaced by "$0.50".
- A 50% discount on "$2" yields "$1". Since we need to have exactly 2 decimal places after a price, we replace "$2" with "$1.00".
Example 2
Input: sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100
Output: "1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$"
Explanation:
Applying a 100% discount on any price will result in 0.
The words representing prices are "$3", "$5", "$6", and "$9".
Each of them is replaced by "$0.00".
Constraints
1 <= sentence.length <= 10^5sentenceconsists of lowercase English letters, digits,' ', and'$'.sentencedoes not have leading or trailing spaces.- All words in
sentenceare separated by a single space. - All prices will be positive numbers without leading zeros.
- All prices will have at most
10digits. 0 <= discount <= 100
Solution
Method 1 – String Parsing and Formatting
Intuition
The key idea is to identify words that represent prices (start with $ and followed by digits), apply the discount, and format the result to two decimal places. We process each word, check if it's a price, and update it accordingly.
Approach
- Split the sentence into words.
- For each word:
- Check if it starts with
$and the rest are digits. - If yes, parse the number, apply the discount, and format to two decimals.
- Otherwise, keep the word unchanged.
- Join the processed words back into a sentence.
Code
C++
class Solution {
public:
string discountPrices(string sentence, int discount) {
stringstream ss(sentence);
string word, ans;
while (ss >> word) {
if (word.size() > 1 && word[0] == '$' && all_of(word.begin() + 1, word.end(), ::isdigit)) {
long long val = stoll(word.substr(1));
double price = val * (1 - discount / 100.0);
char buf[20];
sprintf(buf, "$%.2f", price + 1e-8);
ans += string(buf) + " ";
} else {
ans += word + " ";
}
}
if (!ans.empty()) ans.pop_back();
return ans;
}
};
Java
class Solution {
public String discountPrices(String sentence, int discount) {
String[] arr = sentence.split(" ");
StringBuilder ans = new StringBuilder();
for (String w : arr) {
if (w.length() > 1 && w.charAt(0) == '$' && w.substring(1).chars().allMatch(Character::isDigit)) {
long val = Long.parseLong(w.substring(1));
double price = val * (1 - discount / 100.0);
ans.append(String.format("$%.2f", price)).append(" ");
} else {
ans.append(w).append(" ");
}
}
return ans.toString().trim();
}
}
Python
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
ans: list[str] = []
for w in sentence.split():
if len(w) > 1 and w[0] == '$' and w[1:].isdigit():
val: int = int(w[1:])
price: float = val * (1 - discount / 100)
ans.append(f"${price:.2f}")
else:
ans.append(w)
return ' '.join(ans)
Complexity
- ⏰ Time complexity:
O(N)where N is the length of the sentence (each word is processed once). - 🧺 Space complexity:
O(N)for storing the result.