Loading... > https://leetcode.cn/problems/apply-discount-to-prices/description/?envType=daily-question&envId=2024-05-02 字符串处理问题,模拟即可。注意边界条件。 ```c++ class Solution { public: std::string discountPrices(std::string sentence, int discount) { const int n = sentence.length(); std::string res; int begin = 0, end = 1; while (end <= n) { bool isNum = true; while (end < n && sentence[end] != ' ') { if (isNum && (sentence[end] < '0' || sentence[end] > '9')) isNum = false; end++; } if (!isNum || sentence[begin] != '$' || end - begin == 1) { res += sentence.substr(begin, end - begin + 1); begin = end + 1, end += 2; continue; } long long num = std::stoll(sentence.substr(begin + 1, end - begin - 1)); std::string concession = std::to_string(((double)num * (double )(100 - discount) + 0.5) / 100.0); res += "$" + concession.substr(0, concession.find('.') + 3); if (end != n) res += " "; begin = end + 1, end += 2; } return res; } }; ``` - 时间复杂度:$O(n)$ ,其中 $n$ 为字符串的长度。 - 空间复杂度:$O(n)$ 。 最后修改:2024 年 06 月 18 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏