LeetCode 771. Jewels and Stones Java Solution

·

1 min read

Problem

Jewels and Stones - LeetCode

Solution Approach

  • This problem is about checking whether each character from one input string exists in another input string.

  • Since each character needs to be checked at least once, the time complexity is O(n^2), where n is the length of the input string.

  • It tests your basic string handling skills.

  • To solve it, you need to understand the toCharArray() method and how to compare characters using the char data type in Java.

Java's Primitive Data Types and Reference Data Types

https://github.com/eunhanlee/LeetCode_771_JewelsandStones_Solution.git

Time Complexity: O(n^2), Space Complexity: O(1)

class Solution {
    /**
     * Method to count the number of jewels in the stones.
     *
     * @param jewels The string representing types of jewels.
     * @param stones The string representing the stones you have.
     * @return The number of jewels found in the stones.
     */
    public int numJewelsInStones(String jewels, String stones) {
        int counter = 0;

        for (char stone : stones.toCharArray()) {
            for (char jewel : jewels.toCharArray()) {
                if (stone == jewel) {
                    counter++;
                }
            }
        }

        return counter;
    }
}