algoadvance

Leetcode 3120. Count the Number of Special Characters I

Problem Statement

You are given a string s and a set of special characters. Your task is to count the number of occurrences of these special characters in the string s.

Return the count of special characters in the string.

Clarifying Questions

  1. What characters are considered special?
    • The problem defines that a set of special characters will be given. It’s not predefined.
  2. What should be the input format?
    • You will be provided with a string s and a Set<Character> of special characters.
  3. Can the string s be empty?
    • Yes, in which case the function should return 0.
  4. What should be the output format?
    • The function should return an integer count of special characters.
  5. Are there any constraints on the length of the string?
    • The string length is within the limits of a typical LeetCode problem, i.e., it won’t be extraordinarily large.

Strategy

  1. Initialize Counter: Start with a counter set to 0.
  2. Iterate Through String: Loop through each character in the input string.
  3. Check Set Membership: For each character, check if it is in the set of special characters.
  4. Increment Counter: If the character is found in the set, increment the counter.
  5. Return Result: After the loop ends, return the counter’s value.

Code

import java.util.Set;

public class SpecialCharacterCounter {
    public int countSpecialCharacters(String s, Set<Character> specialCharacters) {
        int count = 0;
        for (char c : s.toCharArray()) {
            if (specialCharacters.contains(c)) {
                count++;
            }
        }
        return count;
    }
    
    public static void main(String[] args) {
        // Example usage:
        SpecialCharacterCounter counter = new SpecialCharacterCounter();
        String s = "example!string#with$special*characters";
        Set<Character> specialCharacters = Set.of('!', '#', '$', '*');
        System.out.println(counter.countSpecialCharacters(s, specialCharacters)); // Output: 4
    }
}

Time Complexity

This solution efficiently counts the number of special characters in the given string using a straightforward approach and optimal complexity.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI