leetcode1:宝石和石头

leetcode1:宝石和石头
解法1:双层遍历,比较每个字符的值

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

解法2:用正则方式,将J进行替换,计算替换的字符数

class Solution {
    public int numJewelsInStones(String J, String S) {
        return S.replaceAll("[^" + J + "]", "").length();
    }
}

解法3:利用hashSet的contains方法,只需遍历S字符数组即可
leetcode1:宝石和石头

相关文章: