Skip to main content
Back to problems
#2288
Medium Algorithms

Apply discount to prices

String
33.8% acceptance
Feb 25, 2026
223
1130
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 sequence of digits preceded by a dollar sign. For example, "$100", "$23", and "$6" represent prices while "100", "$", and "$1e5" 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. Note that all prices will contain at most 10 digits.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn discount_prices(sentence: String, discount: i32) -> String {
    let words: Vec<&str> = sentence.split(' ').collect();
    let result: Vec<String> = words.iter().map(|w| {
      let bytes = w.as_bytes();
      if bytes[0] == b'$' && bytes.len() > 1 && bytes[1..].iter().all(|&b| b.is_ascii_digit()) {
        let price: f64 = w[1..].parse().unwrap();
        let discounted = price * (100 - discount) as f64 / 100.0;
        format!("${:.2}", discounted)
      } else {
        w.to_string()
      }
    }).collect();
    result.join(" ")
  }
}