Skip to content

Commit

Permalink
June18: stringstream processing [M]
Browse files Browse the repository at this point in the history
learning stringstream, Time/Space: O(N)
  • Loading branch information
aucker committed Jun 18, 2024
1 parent 069237b commit 2f405dc
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions daily/June18.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <bits/stdc++.h>

#include <iomanip>
#include <sstream>
using namespace std;

class Solution {
public:
/**
* @brief LC: 2288: Apply Discount to Prices
* Time: O(N), Space: O(N)
*
* @param sentence
* @param discount
* @return string
*/
string discountPrices(string sentence, int discount) {
double d = 1 - discount / 100.0;
stringstream ss(sentence);
string ans, w;
while (ss >> w) { // split and add to ans
if (!ans.empty()) {
ans += ' ';
}
if (w.length() > 1 && w[0] == '$' &&
all_of(w.begin() + 1, w.end(), ::isdigit)) {
stringstream s;
s << fixed << setprecision(2) << '$' << stoll(w.substr(1)) * d;
ans += s.str();
} else {
ans += w;
}
}

return ans;
}
};

0 comments on commit 2f405dc

Please sign in to comment.