📌  相关文章
📜  具有相同数量的小写和大写字母的子字符串的数量

📅  最后修改于: 2021-09-06 06:07:45             🧑  作者: Mango

给定字符串S由小写和大写字母组成,任务是找到具有相等数量的小写和大写字母的子串的数量。

例子:

朴素方法:解决给定问题的最简单方法是生成给定字符串S 的所有可能子字符串,如果该子字符串包含相同数量的小写字母和大写字母,则将子字符串的计数加1 。检查所有子字符串后,打印计数值作为结果。

时间复杂度: O(N 3 )
辅助空间: O(1)

有效的方法:可以通过将每个小写和大写字母分别视为1-1来解决给定的问题,然后找到总和为0的子数组的计数。请按照以下步骤解决问题:

  • 初始化一个 HashMap,比如存储所有前缀总和的频率的M。
  • 初始化一个变量,比如currentSum0res0 ,分别存储每个前缀的总和和结果子串的计数。
  • 遍历字符串并执行以下步骤:
    • 如果当前字符为大写,则将currentSum的值增加1 。否则,将currentSum的值减少-1
    • 如果currentSum 的值为0 ,则将res的值增加1
    • 如果currentSum的值存在于映射M 中,则将res的值增加M[currentSum]
    • 将 HashMap McurrentSum的频率增加1
  • 完成上述步骤后,打印res的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the count of
// substrings having an equal number
// of uppercase and lowercase characters
int countSubstring(string& S, int N)
{
    // Stores the count of prefixes
    // having sum S considering uppercase
    // and lowercase characters as 1 and -1
    unordered_map prevSum;
 
    // Stores the count of substrings
    // having equal number of lowercase
    // and uppercase characters
    int res = 0;
 
    // Stores the sum obtained so far
    int currentSum = 0;
 
    for (int i = 0; i < N; i++) {
 
        // If the character is uppercase
        if (S[i] >= 'A' and S[i] <= 'Z') {
            currentSum++;
        }
 
        // Otherwise
        else
            currentSum--;
 
        // If currsum is o
        if (currentSum == 0)
            res++;
 
        // If the current sum exists in
        // the HashMap prevSum
        if (prevSum.find(currentSum)
            != prevSum.end()) {
 
            // Increment the resultant
            // count by 1
            res += (prevSum[currentSum]);
        }
 
        // Update the frequency of the
        // current sum by 1
        prevSum[currentSum]++;
    }
 
    // Return the resultant count of
    // the subarrays
    return res;
}
 
// Driver Code
int main()
{
    string S = "gEEk";
    cout << countSubstring(S, S.length());
 
    return 0;
}


Java
// Java program for the above approach
import java.util.HashMap;
 
class GFG{
 
// Function to find the count of
// substrings having an equal number
// of uppercase and lowercase characters
static int countSubstring(String S, int N)
{
     
    // Stores the count of prefixes
    // having sum S considering uppercase
    // and lowercase characters as 1 and -1
    HashMap prevSum = new HashMap<>();
 
    // Stores the count of substrings
    // having equal number of lowercase
    // and uppercase characters
    int res = 0;
 
    // Stores the sum obtained so far
    int currentSum = 0;
 
    for(int i = 0; i < N; i++)
    {
         
        // If the character is uppercase
        if (S.charAt(i) >= 'A' && S.charAt(i) <= 'Z')
        {
            currentSum++;
        }
 
        // Otherwise
        else
            currentSum--;
 
        // If currsum is 0
        if (currentSum == 0)
            res++;
 
        // If the current sum exists in
        // the HashMap prevSum
        if (prevSum.containsKey(currentSum))
        {
             
            // Increment the resultant
            // count by 1
            res += prevSum.get(currentSum);
        }
 
        // Update the frequency of the
        // current sum by 1
        prevSum.put(currentSum,
                    prevSum.getOrDefault(currentSum, 0) + 1);
    }
 
    // Return the resultant count of
    // the subarrays
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "gEEk";
    System.out.println(countSubstring(S, S.length()));
}
}
 
// This code is contributed by abhinavjain194


Python3
# Python3 program for the above approach
 
# Function to find the count of
# substrings having an equal number
# of uppercase and lowercase characters
def countSubstring(S, N):
     
    # Stores the count of prefixes
    # having sum S considering uppercase
    # and lowercase characters as 1 and -1
    prevSum = {}
 
    # Stores the count of substrings
    # having equal number of lowercase
    # and uppercase characters
    res = 0
 
    # Stores the sum obtained so far
    currentSum = 0
 
    for i in range(N):
         
        # If the character is uppercase
        if (S[i] >= 'A' and S[i] <= 'Z'):
            currentSum += 1
 
        # Otherwise
        else:
            currentSum -= 1
 
        # If currsum is o
        if (currentSum == 0):
            res += 1
 
        # If the current sum exists in
        # the HashMap prevSum
        if (currentSum in prevSum):
             
            # Increment the resultant
            # count by 1
            res += (prevSum[currentSum])
 
        # Update the frequency of the
        # current sum by 1
        if currentSum in prevSum:
            prevSum[currentSum] += 1
        else:
            prevSum[currentSum] = 1
 
    # Return the resultant count of
    # the subarrays
    return res
 
# Driver Code
if __name__ == '__main__':
     
    S = "gEEk"
    print(countSubstring(S, len(S)))
 
# This code is contributed by bgangwar59


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the count of
// substrings having an equal number
// of uppercase and lowercase characters
static int countSubstring(String S, int N)
{
     
    // Stores the count of prefixes
    // having sum S considering uppercase
    // and lowercase characters as 1 and -1
    Dictionary prevSum = new Dictionary();
 
    // Stores the count of substrings
    // having equal number of lowercase
    // and uppercase characters
    int res = 0;
 
    // Stores the sum obtained so far
    int currentSum = 0;
 
    for(int i = 0; i < N; i++)
    {
         
        // If the character is uppercase
        if (S[i] >= 'A' && S[i] <= 'Z')
        {
            currentSum++;
        }
 
        // Otherwise
        else
            currentSum--;
 
        // If currsum is 0
        if (currentSum == 0)
            res++;
 
        // If the current sum exists in
        // the Dictionary prevSum
        if (prevSum.ContainsKey(currentSum))
        {
             
            // Increment the resultant
            // count by 1
            res += prevSum[currentSum];
            prevSum[currentSum] = prevSum[currentSum] + 1;
        }
        else
            prevSum.Add(currentSum, 1);
    }
 
    // Return the resultant count of
    // the subarrays
    return res;
}
 
// Driver Code
public static void Main(String[] args)
{
    String S = "gEEk";
    Console.WriteLine(countSubstring(S, S.Length));
}
}
 
// This code is contributed by Princi Singh


Javascript


输出:
3

时间复杂度: O(N)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live