[LeetCode] Apply Discount to Prices

2288. Apply Discount to Prices

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 non-negative real number preceded by a dollar sign.

  • For example, “$100”, “$23”, and “$6.75” represent prices while “100”, “$”, and “2$3” 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
string parse(string& s, int& i) {
int n = s.length();
string res = "";
while(i < n and s[i] != ' ') {
res.push_back(s[i++]);
}
return res;
}
bool isMoney(string& s) {
if(s[0] != '$') return false;
if(s.length() == 1) return false;
bool dot = false;
for(int i = 1; i < s.length(); i++) {
if(s[i] == '.') {
if(i + 1 == s.length()) return false;
if(i == 1) return false;
dot = true;
} else if(!isdigit(s[i])) return false;
}
return true;
}
double toDobule(string& s) {
return stod(s.substr(1)) + 1e-6;
}
public:
string discountPrices(string sentence, int discount) {
int i = 0, n = sentence.length();
string res = "";
while(i < n) {
string token = parse(sentence, i);
if(isMoney(token)) {
long double cost = toDobule(token);
cost = cost - (cost * discount / 100);
string money = "$" + to_string(cost);
int cut = money.length();
for(int i = 0; i < money.length(); i++) {
if(money[i] == '.') {
cut = i += 2;
}
}
string valid = money.substr(0, cut + 1);
res += valid;
} else res += token;
if(i < n) {
res.push_back(' '); i++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/29/PS/LeetCode/apply-discount-to-prices/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.