Leetcode.2288--价格减免

87 阅读1分钟

题目:

句子 是由若干个单词组成的字符串,单词之间用单个空格分隔,其中每个单词可以包含数字、小写字母、和美元符号 '$' 。
如果单词的形式为美元符号后跟着一个非负实数,那么这个单词就表示一个价格。

例如 "$100""$23""$6.75" 表示价格,而 "100""$""2$3" 不是。
注意:本题输入中的价格均为整数。

给你一个字符串 sentence  和一个整数 discount 。
对于每个表示价格的单词,都在价格的基础上减免 discount% ,并 更新 该单词到句子中。
所有更新后的价格应该表示为一个 恰好保留小数点后两位 的数字。

返回表示修改后句子的字符串。

示例 1:

输入:sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50
输出:"there are $0.50 $1.00 and 5$ candies in the shop"
解释:
表示价格的单词是 "$1""$2" 。 
- "$1" 减免 50% 为 "$0.50" ,所以 "$1" 替换为 "$0.50" 。
- "$2" 减免 50% 为 "$1" ,所以 "$1" 替换为 "$1.00"

示例 2:

输入:sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100
输出:"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$"
解释:
任何价格减免 100% 都会得到 0 。
表示价格的单词分别是 "$3""$5""$6""$9"。
每个单词都替换为 "$0.00"

1.分析题目

我们可以从题目中可以得到的信息,只有$+数字才是表示价格的,discount%是要减去的价格,还有就是要保留小数点两位

2.做题

/**
 * @param {string} sentence
 * @param {number} discount
 * @return {string}
 */
var discountPrices = function(sentence, discount) {
    // 分割字符串
    let arr = sentence.split(' ')
    // 第一个条件,以 $ 开头的要做价格的处理,不然就不做处理
    let reg = /^\$/
    // 定义临时的数组存放我们的元素
    let tempArr = []
    // 第二个条件,只有`$+数字`才是表示价格的,这里是过滤掉一个字符中有两个 $ 符的存在
    let reg2 = /\$/g
    // 第二个条件,只有`$+数字`才是表示价格的,这里是过滤掉 $ 符后面不是数组的存在
    let reg3 = /\D/
    for(let i in arr){
        if( reg.test(arr[i]) && 
            arr[i].match(reg2).length === 1 && 
            arr[i].slice(1).length >= 1 &&
            !reg3.test(arr[i].slice(1))
            ){
            if(discount !== 100){
                let temp = arr[i].slice(1) - arr[i].slice(1) * discount / 100
                tempArr.push(`$${temp.toFixed(2)}`)    
            }else{
                let temp = 0
                tempArr.push(`$${temp.toFixed(2)}`)    
            }
        }else{
            tempArr.push(arr[i])
        }
    }
    return tempArr.join(' ')
};

3.查看别人的代码

const discountPrices = (sentence: string, discount: number): string => {
  return sentence.split(' ').map(item => {
    const convert = (str: string, p1: number) => {
      return `$${(p1 * (1 - (discount / 100))).toFixed(2)}`;
    };
    // 很好的运用了正则, /^\$(\d+)$/ 表示 以 $ 开头(^$)并且以 一个或多个(+)数字(\d)结尾($)
    return item.replace(/^\$(\d+)$/, convert);
  }).join(' ');
};

4.总结

1.正则能力需要提升
2.循环可以用map,forEach,for in,for of,在这题中,用map,forEach的话,可以节省空间复杂度