LeetCode(String) 771. Jewels and Stones

1.问题

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 <= 50
  • jewels and stones consist of only English letters.
  • All the characters of jewels are unique.

2.解决思路

方法1:

1.字符串jewels和stones转换成字符串数组
2.设置变量sum的初始值为0
3.遍历a和b的数组,如果元素相等就加1
4.返回值sum

方法2:

1.设置变量sum的初始值为0
2.遍历stones的字符串元素
3.jewels字符串.indexof(stones字符串的字符),如果没有出现返回字符串位置-1(-1代表不存在),num加一
4.返回值sum

3.代码

代码1

class Solution {
    public int numJewelsInStones(String jewels, String stones) {
        //1.字符串jewels和stones转换成字符串数组
        char[] a = jewels.toCharArray();
        char[] b = stones.toCharArray();
        //2.设置变量sum的初始值为0
        int sum =0;
        //3.遍历a和b的数组,如果元素相等就加1
        for(int i=0;i<a.length;i++){
            for(int j=0;j<b.length;j++){
                if(a[i]==b[j]){
                    sum++;
                }

            }
        }
        //4.返回值sum
        return sum;
    }
}

代码2

class Solution {
    public static int numJewelsInStones(String jewels, String stones) {
        int sum = 0;//1.设置变量sum的初始值为0
        for (int i = 0 ; i < stones.length(); i ++) {//2.遍历stones的字符串元素
            if(jewels.indexOf(stones.charAt(i)) != -1) {//3.jewels字符串.indexof(stones字符串的字符),如果没有出现返回字符串位置-1(-1代表不存在),num加一
                sum++;
            }
        }
        return sum;   //4.返回值sum
    }
}

你可能感兴趣的:(#,Leecode,leetcode,算法,职场和发展)