【LeetCode】宝石与石头
2018-03-30 21:25
302 查看
给定字符串
输出:
输出:
耗时:44 ms
耗时:40 ms
耗时:4ms
在Python中,我们使用
Python中对for循环的简写,然后转化为向量形式,可以像Python第二种方法来写。(当然可以用
在C++中,可以直接定义string,计算string的长度使用
C++句尾加分号加分号加分号!
题目网址:https://leetcode-cn.com/problems/jewels-and-stones/description/
J代表你现在拥有代表宝石的类型,和字符串
S代表你拥有的石头。
S中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J中的字母不重复,
J和
S中的所有字符都是字母。字母区分大小写,因此
"a"和
"A"是不同类型的石头。
示例1
输入:J = "aA", S = "aAAbbbb"
输出:
3
示例2
输入:J = "z", S = "ZZ"
输出:
0
Python 解答1
def numJewelsInStones(J, S): i = 0 for s in S: if s in J: i += 1 return i
耗时:44 ms
Python 解答2
def numJewelsInStones(J, S): return sum([s in J for s in S])
耗时:40 ms
C++ 解答
int numJewelsInStones(string J, string S) { int i = 0; for(int j=0; j<J.length(); j++) { for(int s=0; s<S.length(); s++) { if(J[j] == S[s]) i++; } } return i; }
耗时:4ms
心得
本道题的运行耗时,C++很轻松地碾压了Python,快了整整一个量级。其中在编程的过程中,有些点需要注意,以及有些小技巧以后也可以使用:在Python中,我们使用
in可以直接单个字符是否在一个字符串中,其实相当于对字符串使用了
set()函数转化为list。
Python中对for循环的简写,然后转化为向量形式,可以像Python第二种方法来写。(当然可以用
numpy包来直接计算,但是这里不能用)
在C++中,可以直接定义string,计算string的长度使用
.length()。
C++句尾加分号加分号加分号!
题目网址:https://leetcode-cn.com/problems/jewels-and-stones/description/
相关文章推荐
- LeetCode 刷题(python)之 宝石与石头
- Leetcode-403.Frog Jump(青蛙跳石头)
- 测试女巫之石头变宝石篇
- [LeetCode]292. Nim Game(轮流拿掉石头)
- leetcode Invert Binary Tree python
- LeetCode221. Maximal Square
- LeetCode-Sqrt(x)
- [leetcode]N-Queens II
- leetcode - 33. Search in Rotated Sorted Array
- [LeetCode]539. Minimum Time Difference
- Leetcode: 15. 3Sum
- [LeetCode] 206-Reverse Linked List
- [LeetCode] 477. Total Hamming Distance(位操作)
- LeetCode 638: Shopping Offers
- Leetcode解题笔记 53. Maximum Subarray [Easy] 动态规划
- LeetCode-Max Points on a Line
- 32_leetcode_Merge Intervals
- LeetCode 之 string字符串二
- Leetcode Compare Version Numbers
- LEETCODE: Wildcard Matching