1. 问题描述
- 描述:查找字符串stones中有几个字符在字符串jewels中。
- 输入:stones和jewels
- 输出:stones中字符在jewels数量
2. 解题思路1
- 关键点:遍历stones中字符,判断字符是否在jewels中。
- 解题步骤:
- a. 遍历stones
- b. 判断字符存在
- javascript
/**
* @param {string} jewels
* @param {string} stones
* @return {number}
*/
var numJewelsInStones = function(jewels, stones) {
let jewelsCount = 0;
for (let s of stones){
if(jewels.includes(s)){
jewelsCount++;
}
}
return jewelsCount;
};
- Python
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
jewels_count = 0
for s in stones:
if s in jewels:
jewels_count = jewels_count + 1
return jewels_count
3. 解题思路2
- 关键点:正则匹配
- 解题步骤:
- a. 获取stones原长度
- b. 删除包含在jewels中的字符
- c. 获取当前stones长度
- d. 原长度减去当前长度
- javascript
/**
* @param {string} jewels
* @param {string} stones
* @return {number}
*/
var numJewelsInStonesReg = function(jewels, stones) {
let stonesLength = stones.length;
let jewelsReg = eval(`/${jewels.split('').join('|')}/g`);
stones = stones.replace(jewelsReg,'');
return stonesLength - stones.length;
};
4. 最后
都不是最优,再接再厉!