DEV Community

Cover image for 3121. Count the Number of Special Characters II
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on • Edited on

3121. Count the Number of Special Characters II

3121. Count the Number of Special Characters II

Easy

You are given a string word. A letter c is called special if it appears both in lowercase and uppercase in word, and every lowercase occurrence of c appears before the first uppercase occurrence of c.

Return the number of special letters in word.

Example 1:

  • Input: word = "aaAbcBC"
  • Output: 3
  • Explanation: The special characters are 'a', 'b', and 'c'.

Example 2:

Input: word = "abc"
Output: 0
Explanation: There are no special characters in word.

Example 3:

Input: "AbBCab"
Output: [0,1]
Explanation: There are no special characters in word.

Constraints:

  • 1 <= word.length <= 2 * 105
  • word consists of only lowercase and uppercase English letters.

Solution:

class Solution {

    /**
     * @param String $word
     * @return Integer
     */
    function numberOfSpecialChars($word) {
        $first = array_fill(0, ord('z') + 1, 0);
        $last = array_fill(0, ord('z') + 1, 0);
        for ($i = 1; $i <= strlen($word); ++$i) {
            $j = ord($word[$i - 1]);
            if ($first[$j] == 0) {
                $first[$j] = $i;
            }
            $last[$j] = $i;
        }
        $ans = 0;
        for ($i = 0; $i < 26; ++$i) {
            if ($last[ord('a') + $i] && $first[ord('A') + $i] && $last[ord('a') + $i] < $first[ord('A') + $i]) {
                ++$ans;
            }
        }
        return $ans;
    }
}
Enter fullscreen mode Exit fullscreen mode

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay