每日一道Leetcode算法——Jewels and Stones——2019.01.14

你得到的字符串J代表珠宝的类型,S代表你拥有的宝石。 S中的每个分子都是你拥有的一种宝石。你想知道你有多少宝石是规定类型的珠宝。
J中的字母保证每个都不同,J和S中的所有字符都是字母。字母区分大小写,因此“a”被认为是与“A”不同类型的宝石。

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3

Example 2:

Input: J = "z", S = "ZZ"
Output: 0
注:S和J将由字母组成,长度最多为50。
J中的字符是截然不同的。

 解体思路:

其实这题就是一个字符串J,一个字符串S,在S中寻找J字符串中每个字节出现的次数。

所以我们构建两层循环,第一层将字符串J拆成一个个char,第二层将字符串S拆成一个个char,然后将字符串J中的每个char去字符串S中寻找一次。

由于备注中说明J中无重复的字符,所以不用特殊处理,每次找到给总数+1就够了。

package cn.leetcode;

/**
 * You're given strings J representing the types of stones that are jewels,
 * and S representing the stones you have.
 * Each character in S is a type of stone you have.
 * You want to know how many of the stones you have are also jewels.
 * 
 * The letters in J are guaranteed distinct, and all characters in J and S are letters.
 * Letters are case sensitive, so "a" is considered a different type of stone from "A".
 * 
 * Example 1:
 * Input: J = "aA", S = "aAAbbbb"
 * Output: 3
 * 
 * Example 2:
 * Input: J = "z", S = "ZZ"
 * Output: 0
 * 
 * Note:
 * S and J will consist of letters and have length at most 50.
 * The characters in J are distinct.
 *
 * @author kimtian
 */
public class JewelsAndStones {
    public static int numJewelsInStones(String J, String S) {
        int sum = 0;
        // 字符串S不在规定的范围中,则返回0
        if (S.length() > 50 && S.length() <= 0) {
            return 0;
        } else {
            //先遍历J字符串
            for (int i = 0; i < J.length(); i++) {
                char j = J.charAt(i);
                //再遍历S字符串
                for (int z = 0; z < S.length(); z++) {
                    //如果中是否包含这个char,则总数加1
                    if (S.charAt(z) == j) {
                        sum++;
                    }
                }
            }
        }
        return sum;
    }

    /**
     * 测试类
     *
     * @param args
     */
    public static void main(String[] args) {
        //两个字符串都为空
        System.out.println(numJewelsInStones("", ""));
        //结果应该为3
        System.out.println(numJewelsInStones("Aa", "aAAbbbb"));
        //结果应该为2
        System.out.println(numJewelsInStones("A", "aAAbbbb"));
        //结果应该为1
        System.out.println(numJewelsInStones("a", "aAAbbbb"));
        //因为区分大小写,所以结果应该为0
        System.out.println(numJewelsInStones("B", "aAAbbbb"));
    }
}

猜你喜欢

转载自blog.csdn.net/third_/article/details/86497648