771. Jewels and Stones

Problem:

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".


题目:题目大致的意思计算S中的字符出现在J中的数量....

代码1:打败50%多,

class Solution {
    public int numJewelsInStones(String J, String S) {
        if(J.length()==0)
            return 0;
        HashSet<String> hashSet = new HashSet<String>();
        int ret = 0;
        for(int i = 0; i < J.length(); i ++){
        if(!hashSet.contains(J.substring(i, i+1)))
        hashSet.add(J.substring(i,i+1));
        }
        for(int i=0;i<S.length();i++){
            if(hashSet.contains(S.substring(i, i+1))) {
            ret++;
            }
        
        }
        return ret;
    }

}

看过排名靠前的后代码很简单,主要感觉是要对Java足够熟练,对对象的成员函数了解程度。就像string中的toCharArray()的使用。

class Solution {
    public int numJewelsInStones(String J, String S) {
        if(J.length()==0)
            return 0;
        int ret = 0;
        for(char c : S.toCharArray()){
        if(J.indexOf(c)!=-1) {
        ret ++;
        }
        }
        return ret;
    }
}

猜你喜欢

转载自blog.csdn.net/hc1017/article/details/80048404