You're given strings J
representing the types of stones that are jewels, and S
representing the stones you have. Each character in S
is 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
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
此题是找出J中的字符在S中的个数,本人的解法时间复杂度为O(n),空间复杂度为O(1),就是感觉代码稍嫌繁琐,Accepted代码如下:
class Solution {
public int numJewelsInStones(String J, String S) {
int lj = J.length();
int ls = S.length();
if (lj == 0 || ls == 0) {
return 0;
}
int[] A = new int[26];
int[] B = new int[26];
for (int i = 0; i < lj; i++) {
char c = J.charAt(i);
if ( c >= 'a' && c <= 'z') {
A[c - 'a']++;
}
if ( c >= 'A' && c <= 'Z') {
B[c - 'A']++;
}
}
int sum = 0;
for (int i = 0; i < ls; i++) {
char c = S.charAt(i);
if ( c >= 'a' && c <= 'z') {
if (A[c - 'a'] > 0) {
sum++;
}
}
if ( c >= 'A' && c <= 'Z') {
if (B[c - 'A'] > 0) {
sum++;
}
}
}
return sum;
}
}