GFG 192 Absolute Difference Array
您是打尖儿还是住店呢
2025年02月03日 09:01
收录于文集
共499篇

You are given a string s of lowercase English letters. Your task is to  nd for each index i, the

absolute di erence between the frequency of vowels, and the frequency of consonants in the

substring s[0...i]. Return an array of length n, where n is the length of string s, and the ith element is the absolute difference between the frequency of vowels, and the frequency of consonants in the substring s[0...i]. 

Examples:

Input: s = "geek"

Output: [1, 0, 1, 0]

Explanation: The substring s[0...0] = "g". The frequency of vowels is 0, and the 

frequency of consonants is 1. The absolute difference is 1.

The substring s[0...1] = "ge". The frequency of vowels is 1, and the frequency of 

consonants is 1. The absolute difference is 0.

The substring s[0...2] = "gee". The frequency of vowels is 2, and the frequency of 

consonants is 1. The absolute difference is 1.

The substring s[0...3] = "geek". The frequency of vowels is 2, and the frequency of 

consonants is 2. The absolute difference is 0.

Input: s = "abcde"

Output: [1, 0, 1, 2, 1]

Explanation: The substring s[0...0] = "a". The frequency of vowels is 1, and the 

frequency of consonants is 0. The absolute difference is 1.

The substring s[0...1] = "ab". The frequency of vowels is 1, and the frequency of 

consonants is 1. The absolute difference is 0.

The substring s[0...2] = "abc". The frequency of vowels is 1, and the frequency of 

consonants is 2. The absolute difference is 1.

The substring s[0...3] = "abcd". The frequency of vowels is 1, and the frequency of 

consonants is 3. The absolute difference is 2.

The substring s[0...4] = "abcde". The frequency of vowels is 2, and the frequency of 

consonants is 3. The absolute difference is 1.

Constraints:

1 ≤ |s| ≤ 10

----

元音跟辅音的绝对值之差。

直接简单计算模拟即可。

代码块
JavaScript
自动换行
复制代码
 public int[] absDifference(String s) {
        // code here
        int n=s.length();
        int[]a=new int[n];
        String vowel="aeiou";
        int cnt=0;
        for (int i = 0; i < n; i++) {
            int len=i+1;
            String tem=String.valueOf(s.charAt(i));
            if(vowel.contains(tem)){
                cnt++;
            }
            a[i]=Math.abs(len-2*cnt);
        }
        return a;
    }
复制成功