問題:
字串 J是寶石的集合,每個字元代表一種寶石,S字串則是一堆石頭集合,每個字元代表一顆石頭,需要找S中,有多少J裡面的寶石.
註:大小寫為不相同的,例如:大寫A跟小寫a代表不同的寶石.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public int numJewelsInStones(String J, String S) { if(J.length()>1){ return numJewelsInStones(J.substring(0,1),S)+numJewelsInStones(J.substring(1),S); } int i =0; for(char a:S.toCharArray()){ if(a==J.charAt(0)) i++; } return i; } }
|
目前找到第一個版本有一個錯誤
test case: J=”aAa” S=”aAAbbbb” Output= 4 Expected=3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public int numJewelsInStones(String J, String S) { Set<Character> Jewels = new HashSet<Character>(); for (char j :J.toCharArray()){ Jewels.add(j); } int count=0; for(char s: S.toCharArray()){ if(Jewels.contains(new Character(s))) count++; } return count; } }
|