From 2f405dc33e539ec448dc820b46cc1790991b47f1 Mon Sep 17 00:00:00 2001 From: aucker Date: Tue, 18 Jun 2024 18:55:29 +0800 Subject: [PATCH] June18: stringstream processing [M] learning stringstream, Time/Space: O(N) --- daily/June18.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 daily/June18.cpp diff --git a/daily/June18.cpp b/daily/June18.cpp new file mode 100644 index 0000000..aa562ad --- /dev/null +++ b/daily/June18.cpp @@ -0,0 +1,37 @@ +#include + +#include +#include +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; + } +}; \ No newline at end of file