-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
learning stringstream, Time/Space: O(N)
- Loading branch information
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |