May LeetCoding Challenge2 之 HashSet的使用

Set常用方法:add,remove,contains,size...
HashSet无序,与HashMap的key作用相同。
TreeSet有序,与TreeMap的key作用相同。
 
两种解法:
1.遍历字符串S,判断S中的字符能否在J中找到对应的字符,如果找到res+1,跳出当前循环,再判断S中的下一个字符。
2.将J中的所有字符存入set集合中,遍历字符串S,如果字符在set集合中,res+1。
 
JAVA
class Solution {
    public int numJewelsInStones(String J, String S) {
        int res = 0;
        for(char s: S.toCharArray()){
            for(char j: J.toCharArray()){
                if(s == j){
                    res ++;
                    break;
                }
            }
        }
        return res;
    }
}

 

class Solution {
    public int numJewelsInStones(String J, String S) {
        Set<Character> set = new HashSet<>();
        int res = 0;
        for(char j: J.toCharArray()){
            set.add(j);
        }
        for(char s: S.toCharArray()){
            if(set.contains(s)) res++;
        }
        return res;
    }
}

 

Python3

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        res = 0
        for s in S:
            if s in J:
                res += 1
        return res

 

posted @ 2020-05-03 20:28  yawenw  阅读(112)  评论(0编辑  收藏  举报