LeetCode771-宝石与石头
作者:互联网
非商业,LeetCode链接附上:
https://leetcode-cn.com/problems/jewels-and-stones/
进入正题。
题目:
给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
示例:
示例 1:
输入: J = "aA", S = "aAAbbbb"
输出: 3
示例 2:
输入: J = "z", S = "ZZ"
输出: 0
注意:
S 和 J 最多含有50个字母。
J 中的字符不重复。
代码实现:
//暴力法 public int numJewelsInStones(String J, String S) { int jewelsCount = 0; int jewelsLength = J.length(), stonesLength = S.length(); for (int i = 0; i < jewelsLength; i++) { char jewel = J.charAt(i); for (int j = 0; j < stonesLength; j++) { char stone = S.charAt(j); if(jewel == stone) { jewelsCount++; } } } return jewelsCount; } //时间复杂度O(mn),空间复杂度O(1) //哈希集合 public int numJewelsInStones(String J, String S) { int jewelsCount = 0; Set<Character> jewelsSet = new HashSet<>(); int jewelsLength = J.length(), stonesLength = S.length(); for (int i = 0; i < jewelsLength; i++) { char jewel = J.charAt(i); jewelsSet.add(jewel); } for (int i = 0; i < stonesLength; i++) { char stone = S.charAt(i); if(jewelsSet.contains(stone)) { jewelsCount++; } } return jewelsCount; } //时间复杂度O(m + n),其中m是字符串J度长度,n是字符串S的长度 //空间复杂度O(m)
分析:
之所以把这道题单独拎出来,是在写的时候感觉到了暴力方法的暴力美学,不掺杂多余的技巧,也不需要太多的解释。
有一点要注意的是chatAt()方法的使用,之前偶尔会将字符串转化成字符数组,这样就在无形中增加了空间复杂度。
暴力方法基本都不会是最终最优的解法,在解算法题或人生中也都逐渐的远离暴力的解决问题的方式吧。
--End
标签:jewelsLength,String,宝石,int,复杂度,石头,++,jewelsCount,LeetCode771 来源: https://www.cnblogs.com/heibingtai/p/14031189.html