You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone from "A".
吧
Example 1:
Input: jewels = "aA", stones = "aAAbbbb" Output: 3
Example 2:
Input: jewels = "z", stones = "ZZ" Output: 0
Constraints:
1 <= jewels.length, stones.length <= 50jewels and stones consist of only English letters.jewels are unique.就是判断一个字符串里的字符有多少个出现在了另一个字符串里……没啥意思……就把jewels变成set然后遍历stones看在不在set里……
- class Solution {
- public int numJewelsInStones(String jewels, String stones) {
- Set<Character> set = new HashSet<>();
- for (char c : jewels.toCharArray()) {
- set.add(c);
- }
- int count = 0;
- for (char c : stones.toCharArray()) {
- if (set.contains(c)) {
- count++;
- }
- }
- return count;
- }
- }
也可以直接用indexOf……
- class Solution {
- public int numJewelsInStones(String jewels, String stones) {
- int count = 0;
- for (char c : stones.toCharArray()) {
- if (jewels.indexOf(c) != -1) {
- count++;
- }
- }
- return count;
- }
- }
还有人用regex的……Loading...