Topic
The given string J
represents the type of gem in the stone, and S
the string represents the stone you own. S
Each character represents a type of stone you have, and you want to know how many of the stones you have are gems. The J
letters in are not repeated, J
and all the S
characters in are letters. Letters are case-sensitive, so "a"
and "A"
are different types of stones.
Analysis
Give two strings, comparing the number of repetitions of a string in the data in another string
- Requirements:
Case-sensitive letters
Total number of claims
Test data
Input: J = "aA", S = "aAAbbbb"
output: 3
Input: J = "z", S = "ZZ"
output: 0
Reference answer
Algorithm idea:
- First, we find the number of stones in s that are repeated in the array
- The traversal data is compared with the characters in J.
public int Numjewelsinstones (string J, String S) {
int count = 0;
map<string,integer> map = new hashmap<string,integer> ();
for (int i =0;i<s.length (); i++) {
String SV = string.valueof (S.charat (i));
if (Map.containskey (SV)) {
Map.put (Sv,map.get (SV) +1);
}else{
Map.put (sv,1);
}
}
for (int i =0;i<j.length (); i++) {
Char s =j.charat (i);
Count=map.get (string.valueof (s)) ==null?0+count:map.get (string.valueof (s)) +count;
}
return count;
}
5, Excellent solution
Class Solution {
public int Numjewelsinstones (string J, String S) {
int result = 0;
Char[] s = new char[128];
for (char C:s.tochararray ()) {
s[c]++;
}
for (char J:j.tochararray ()) {
Result + = S[j];
}
return result;
}
}
Fifth algorithm-Gem and stone algorithm