Loading

771. [字符串][哈希表]宝石与石头

771. 宝石与石头

方法一:双层循环

// 执行用时: 1 ms , 在所有 Java 提交中击败了 99.67% 的用户 
// 内存消耗: 37.1 MB , 在所有 Java 提交中击败了 69.25% 的用户

class Solution {
    public int numJewelsInStones(String J, String S) {
        int cnt = 0;
        for(int i = 0; i < S.length(); i++){
            for(int j = 0; j < J.length(); j++){
                if (S.charAt(i) == J.charAt(j)){
                    cnt++;
                }
            }
        }
        return cnt;
    }
}

方法二:哈希

// 执行用时: 1 ms , 在所有 Java 提交中击败了 99.67% 的用户
// 内存消耗: 37.2 MB , 在所有 Java 提交中击败了 54.84% 的用户

class Solution {
    public int numJewelsInStones(String J, String S) {
        int jewelsCount = 0;
        Set<Character> jewelsSet = new HashSet<Character>();
        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;
    }
}
posted @ 2020-10-24 11:47  上海井盖王  阅读(56)  评论(0)    收藏  举报