120、宝石与石头

题目描述

class Solution {
    public int numJewelsInStones(String J, String S) {
        char [] Jtem = J.toCharArray();
		char [] Stem = S.toCharArray();
		int count = 0;
		
		for (int i = 0; i < S.length(); i++) {
			char c = Stem[i];
			if(-1 != J.indexOf(c))
				count++;
			
		}
		
		
		return count;
    }
}

很简单的一道题目,我竟然花了六分钟,原因是我将if后用括号了,我去

class Solution {
    public int numJewelsInStones(String J, String S) {
        char [] Jtem = J.toCharArray();
		char [] Stem = S.toCharArray();
		int count = 0;
		
		for (int i = 0; i < S.length(); i++) {
			char c = Stem[i];
			if(-1 != J.indexOf(c))
				count++;
			
		}
		
		
		return count;
    }
}

使用HashMap进行,时间会缩短

class Solution {
    public int numJewelsInStones(String J, String S) {
        HashMap<Character, Integer> map = new HashMap<>();
		for (int i = 0; i < J.length(); i++) {
			map.put(J.charAt(i), i);
			
		}
		
		int count = 0;
		for (int i = 0; i < S.length(); i++) {
			if(map.containsKey(S.charAt(i)))
				count++;
			
		}
		
		return count;
        
    }
}

排名靠前的代码

class Solution {
    public int numJewelsInStones(String J, String S) {
         char[] stoneArray = S.toCharArray();
        
        int jewCnt = 0 ;
        for(char tmp:stoneArray){
            if(J.indexOf(tmp) != -1){
                jewCnt++;
            }
        }
        return jewCnt;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/85196357