leetcode题解——771. 宝石与石头
2019-06-02 22:32
916 查看
给定字符串
J代表石头中宝石的类型,和字符串
S代表你拥有的石头。
S中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J中的字母不重复,
J和
S中的所有字符都是字母。字母区分大小写,因此
"a"和
"A"是不同类型的石头。
示例1
输入: J = "aA", S = "aAAbbbb" 输出: 3
示例2
输入: J = "z", S = "ZZ" 输出: 0
C++:
最简单的办法,暴力查找
class Solution { public: int numJewelsInStones(string J, string S) { int count = 0; for (int i = 0; i < J.length(); i++) { for (int j = 0; j < S.length(); j++) { // 很遗憾,这样做的话,时间复杂度为O(n^2) if (J[i] == S[j]) { count++; } } } return count; } };
Python:
Python相比C++,写法上看起来更加简单一些,但是时间还是暴力破解
def numJewelsInStones(J: str, S: str) -> int: count = 0 for stone in S: if stone in J: # 虽然看上去只有一个for循环,实际上in也是for(未考证,后续看源码确定) count = count + 1 # 所以,时间复杂度还是O(n^2) return count
相关文章推荐
- Leetcode 771. 宝石与石头
- Leetcode 771.宝石与石头
- LeetCode编程771:宝石与石头
- LeetCode每日刷题Day1--- 771 宝石与石头
- Leetcode771.宝石与石头(python)
- LeetCode 第771题 宝石与石头/Jawels and Stones
- Leetcode771宝石与石头
- LeetCode宝石与石头(C语言)
- LeetCode 刷题(python)之 宝石与石头
- leetcode刷题思路总结_宝石与石头
- 【LeetCode】宝石与石头
- (Python)LeetCode刷题笔记——771、宝石与石头
- Leetcode刷题1-771.宝石与石头(C++)
- Leetcode:宝石与石头
- 【LeetCode题解】121. Best Time to Buy and Sell Stock
- LeetCode题解(python)-26. 删除排序数组中的重复项
- leetcode题解||Container With Most Water问题
- leetcode题解-344. Reverse String && 541. Reverse String II && 345. Reverse Vowels of a String
- LeetCode(3)题解: Longest Palindromic Substring
- leetcode 题解 1. Two Sum