100291. 统计特殊字母的数量 II

给你一个字符串 word。如果 word 中同时出现某个字母 c 的小写形式和大写形式,并且 每个 小写形式的 c 都出现在第一个大写形式的 c 之前,则称字母 c 是一个 特殊字母 。

返回 word 中 特殊字母 的数量。

 

示例 1:

输入:word = "aaAbcBC"

输出:3

解释:

特殊字母是 'a''b' 和 'c'

示例 2:

输入:word = "abc"

输出:0

解释:

word 中不存在特殊字母。

示例 3:

输入:word = "AbBCab"

输出:0

解释:

word 中不存在特殊字母。

 

提示:

  • 1 <= word.length <= 2 * 105
  • word 仅由小写和大写英文字母组成。
class Solution {
    public int numberOfSpecialChars(String word) {
        int res = 0;
        Map<Character, Integer> lowerMap = new HashMap<>();
        Map<Character, Integer> upperMap = new HashMap<>();
        for(int i =0;i<word.length();i++){
            char c = word.charAt(i);
            if(c>='a' && c <='z') {
                lowerMap.put(c,i);
            }
            else if (c>='A' && c<='Z'  && !upperMap.containsKey(c)){
                upperMap.put(c, i);
            }
        }
        for(Map.Entry<Character,Integer> entry : lowerMap.entrySet()){
            char lower = entry.getKey();
            int position = entry.getValue();
            char upper = (char) (lower-32);
            if(upperMap.containsKey(upper)){
                if(position < upperMap.get(upper)){
                    res += 1;
                }

            }
        }
        return res;
    }
}

 

posted @ 2024-04-21 12:03  Heinrich♣  阅读(16)  评论(0编辑  收藏  举报