[JavaScript 刷题] 字符串 - 价格减免, leetcode 2288

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:2288. Apply Discount to Prices

题目

如下:

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 non-negative real number preceded by a dollar sign.

  • For example, "$100", "$23", and "$6.75" represent prices while "100", "$", and "2$3" 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.

解题思路

其实这道题麻烦的点就在于将具体的金额转换成数字,如题目中给出的案例:

Input: sentence = “there are $1 $2 and 5$ candies in the shop”, discount = 50

Output: “there are $0.50 $1.00 and 5$ candies in the shop”

很明显 5$ 就不是一个正确的数字,因此这里不应该进行转换。

题目中给的都是需求比较明确的,在做 weekly contest 的时候碰到一个:"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$",这个 $10$ 对于其他语言来说可能不是问题,但是对于 JavaScript 来说,如果不另外处理就会报错……

原因是因为 JavaScript 在对数字进行转换的时候,它会取前面几个合法的值,$10$ 这里就会被转为 10,而不会报错。

其实用 Regex 来解题就很方便,偏偏我并不是很擅长 Regex,平常遇到需要用 Regex 的需求都是直接上网搜的,这个时候就尴尬了……不过也不是完全没办法,可以将其转换为数字后,使用 == 去判断数字与字符串是否相等。

使用 JavaScript 解题

/**
 * @param {string} sentence
 * @param {number} discount
 * @return {string}
 */
var discountPrices = function (sentence, discount) {
  const strs = sentence.split(" ");

  for (let i = 0; i < strs.length; i++) {
    const currSec = strs[i];
    const price = parseFloat(currSec.substr(1, currSec.length));
    if (currSec[0] === "$" && !isNaN(price)) {
      if (discount === 100) strs[i] = "$0.00";
      else {
        const discountedPrice = ((price * discount) / 100).toFixed(2);
        strs[i] = "$" + discountedPrice;
      }
    }
  }

  return strs.join(" ");
};
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐