classSolution: defnumJewelsInStones(self, jewels: str, stones: str) -> int: returnsum(s in jewels for s in stones)
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intnumJewelsInStones(string jewels, string stones){ int jewelsCount = 0; int jewelsLength = jewels.length(), stonesLength = stones.length(); for (int i = 0; i < stonesLength; i++) { char stone = stones[i]; for (int j = 0; j < jewelsLength; j++) { char jewel = jewels[j]; if (stone == jewel) { jewelsCount++; break; } } } return jewelsCount; } };
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11
var numJewelsInStones = function(jewels, stones) { jewels = jewels.split(''); return stones.split('').reduce((prev, val) => { for (const ch of jewels) { if (ch === val) { return prev + 1; } } return prev; }, 0); };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12
funcnumJewelsInStones(jewels string, stones string)int { jewelsCount := 0 for _, s := range stones { for _, j := range jewels { if s == j { jewelsCount++ break } } } return jewelsCount }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
intnumJewelsInStones(char * jewels, char * stones) { int jewelsCount = 0; int jewelsLength = strlen(jewels), stonesLength = strlen(stones); for (int i = 0; i < stonesLength; i++) { char stone = stones[i]; for (int j = 0; j < jewelsLength; j++) { char jewel = jewels[j]; if (stone == jewel) { jewelsCount++; break; } } } return jewelsCount; }