p54 石头中珠宝的数量 (leetcode 771)
一:解题思路
第一种方法:暴力破解法:Time:O(m*n),Space:O(1)
第二种方法:利用一个哈希表,Time:O(m+n),Space:O(k)
二:完整代码示例 (C++版和Java版)
第一种方法C++:
class Solution { public: int numJewelsInStones(string J, string S) { int count = 0; if (J.size() == 0||S.size()==0) return 0; for (int i = 0; i < J.size(); i++) { for (int j = 0; j < S.size(); j++) { if (J[i] == S[j]) { count++; } } } return count; } };
第一种方法Java:
class Solution { public int numJewelsInStones(String J, String S) { int count=0; if(J==null||J.length()==0||S==null||S.length()==0) return 0; for(int i=0;i<J.length();i++) { for(int j=0;j<S.length();j++) { if(J.charAt(i)==S.charAt(j)) count++; } } return count; } }
第二种方法C++:
class Solution { public: int numJewelsInStones(string J, string S) { int count = 0; if (J.size() == 0 || S.size() == 0) return 0; bool d[256] = {0}; for (int i = 0; i < J.size(); i++) { d[J[i]] = true; } for (int i = 0; i < S.size(); i++) { if (d[S[i]]) { count++; } } return count; } };
第二种方法Java:
class Solution { public int numJewelsInStones(String J, String S) { int count=0; if(J==null||J.length()==0||S==null||S.length()==0) return 0; boolean[] d=new boolean[256]; for(int i=0;i<J.length();i++) { d[J.charAt(i)]=true; } for(int i=0;i<S.length();i++) { if(d[S.charAt(i)]) count++; } return count; } }
                    
                
                
            
        
浙公网安备 33010602011771号