771. Jewels and Stones

You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in Sis 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.
题解:
class Solution {
    public int numJewelsInStones(String J, String S) {
        int sum = 0;
        char ss[] = new char[50];
        ss = S.toCharArray();
        for(char s:ss){
            if(J.indexOf(s)!=-1)
                sum+=1;

        }
        return sum;
        
    }
}
这是一道关于字符串的题目,最先想到的做法是把两个字符串拆开两层for循环遍历,在搜索split()方法的时候发现了toCharArray()方法和indexOf(String s) 两个方法 前者可以将字符串转化为字符数组,返回char[] 后者用于判别某字符串是否包含某字串s,若不是返回-1,否则返回其他int
split()方法
stringObj.split(String separator,int limit)
stringObj 
必选项。要被分解的 String 对象或文字。该对象不会被 split 方法修改。

separator 
可选项。字符串或 正则表达式 对象,它标识了分隔字符串时使用的是一个还是多个字符。如果忽
略该选项,返回包含整个字符串的单一元素数组。 

limit
可选项。该值用来限制返回数组中的元素个数。
one liner解法:
public int numJewelsInStones(String J, String S) {
    return S.replaceAll("[^" + J + "]", "").length();
}
正则表达式[^>]表示非>的字符
posted @ 2018-07-24 10:04  zohy  阅读(101)  评论(0编辑  收藏  举报