📜  根据给定条件计算括号的权重

📅  最后修改于: 2021-05-05 01:41:56             🧑  作者: Mango

给定有效的括号字符串S ,任务是根据以下条件找到括号的权重:

  1. “()”的权重为1
  2. “ AB”的权重=“ A”的权重+“ B”的权重(其中,A和B都是独立的有效括号)。例如,“()()”的权重=“()”的权重+“()”的权重
  3. “(A)”的权重=“ A”的权重的2倍(其中,A是独立的有效括号)。例如,“(())”的权重是“()”的权重的2倍

例子:

方法:
可以使用分而治之的方法解决此问题。请按照以下步骤解决问题:

  • 假设输入括号字符串始终有效,即保持平衡。因此,任何左括号’(’具有对应的右括号’)’
  • 考虑输入字符串开头的左括号(开头的括号不能是右括号,否则将无效)。现在,对于此打开括号,相应的关闭括号可以具有以下两个可能的索引中的任何一个。
    1. 在最后,即第(n-1)索引
    2. 开始结束之间的某个位置,即[1,n-2]
  • 如果右方括号的末尾有一个索引,则根据约束编号。 3,括号的总重量将是字符串[1,n-2]的重量的两倍
  • 如果右括号位于开始和结束之间的某个位置,例如中间,则根据限制条件n。在图2中,括号总权重将为字符串[start,mid]的权重与字符串[mid + 1,end]的权重
  • 递归的基本情况将是当字符串只有两个括号时,它们的权重为1,因为它们固有地是有效的。
  • 现在,问题是我们如何才能找到对应于一个开括号的闭括号的索引。这个想法类似于有效的括号检查。我们将使用堆栈数据结构来检查并在HashMap中存储对应的右括号的右括号的索引。
  • 执行以下步骤:
    • 遍历字符串。
    • 如果一个字符是一个左括号,则将其索引推入Stack
    • 如果它是一个括号,请从堆栈中弹出其索引,然后将(popped_index,current_index)对插入HashMap中

下面是上述方法的实现。

C++
// C++ program to implement 
// the above approach 
#include 
using namespace std;
  
// HashMap to store the ending 
// index of every opening bracket 
unordered_map endIndex; 
  
// Function to calculate and store 
// the closing index of each opening 
// bracket in the parenthesis 
void getClosingIndex(string s) 
{ 
    int n = s.length(); 
  
    stack st; 
  
    for(int i = 0; i < n; i++) 
    { 
        if (s[i] == ')')
        { 
              
            // If it's a closing bracket, 
            // pop index of it's corresponding 
            // opening bracket 
            int startIndex = st.top(); 
            st.pop();
              
            // Insert the index of opening 
            // bracket and closing bracket 
            // as key-value pair in the 
            // hashmap 
            endIndex[startIndex] = i; 
        } 
        else
        { 
              
            // If it's an opening bracket, 
            // push it's index into the stack 
            st.push(i); 
        } 
    } 
} 
  
// Function to return the weight of 
// parenthesis 
int calcWeight(string s, int low, int high) 
{ 
      
    // Base case 
    if (low + 1 == high)
    { 
        return 1; 
    } 
  
    else 
    { 
  
        // Mid refers to ending index of 
        // opening bracket at index low 
        int mid = endIndex[low]; 
          
        if (mid == high)
        { 
            return 2 * calcWeight(s, low + 1, 
                                    high - 1); 
        } 
        else
        { 
            return calcWeight(s, low, mid) + 
                   calcWeight(s, mid + 1, 
                              high); 
        } 
    } 
} 
  
// Driver Code
int main()
{
    string input = "(()(()))"; 
    int n = input.length(); 
  
    // Update the closing Index 
    getClosingIndex(input); 
  
    cout << (calcWeight(input, 0, n - 1)) << endl; 
  
    return 0;
}
  
// This code is contributed by divyeshrabadiya07


Java
// Java Program to implement 
// the above approach 
import java.util.*; 
  
public class GFG { 
  
    // HashMap to store the ending 
    // index of every opening bracket 
    static HashMap endIndex 
        = new HashMap(); 
  
    // Function to calculate and store 
    // the closing index of each opening 
    // bracket in the parenthesis 
    public static void getClosingIndex(String s) 
    { 
  
        int n = s.length(); 
  
        Stack st = new Stack(); 
  
        for (int i = 0; i < n; i++) { 
  
            if (s.charAt(i) == ')') { 
  
                // If it's a closing bracket, 
                // pop index of it's corresponding 
                // opening bracket 
                int startIndex = st.pop(); 
  
                // Insert the index of opening 
                // bracket and closing bracket 
                // as key-value pair in the 
                // hashmap 
                endIndex.put(startIndex, i); 
            } 
            else { 
  
                // If it's an opening bracket, 
                // push it's index into the stack 
                st.push(i); 
            } 
        } 
    } 
  
    // Function to return the weight of 
    // parenthesis 
    public static int calcWeight(String s, 
                                int low, 
                                int high) 
    { 
  
        // Base case 
        if (low + 1 == high) { 
            return 1; 
        } 
  
        else { 
  
            // Mid refers to ending index of 
            // opening bracket at index low 
            int mid = endIndex.get(low); 
            if (mid == high) { 
                return 2 * calcWeight(s, low + 1, 
                                    high - 1); 
            } 
            else { 
                return calcWeight(s, low, mid) 
                    + calcWeight(s, mid + 1, 
                                high); 
            } 
        } 
    } 
  
    public static void main(String[] args) 
    { 
        String input = "(()(()))"; 
        int n = input.length(); 
  
        // Update the closing Index 
        getClosingIndex(input); 
  
        System.out.println(calcWeight(input, 
                                    0, n - 1)); 
    } 
}


Python3
# Python3 program to implement the 
# above approach 
  
# Function to calculate and store 
# the closing index of each opening 
# bracket in the parenthesis 
def getClosingIndex(string): 
  
    # Dictionary to store 
    # the ending index of 
    # each opening bracket 
    endIndex = dict() 
  
  
    n = len(string) 
  
    stack = [] 
    for i in range(n): 
        if (string[i]==')'): 
  
            # If it's a closing bracket, 
            # pop index of it's 
            # corresponding 
            # opening bracket 
            startIndex = stack.pop() 
  
            # Put the index of opening 
            # bracket and closing 
            # bracket as key value 
            # pair in the Dictionary 
            endIndex[startIndex] = i 
  
        else: 
  
            # If it's an opening bracket, 
            # push it's index into 
            # the stack 
            stack.append(i) 
    return endIndex 
      
# Function to return the weight 
# of parenthesis 
def calcWeight(s, low, 
                high, endIndex): 
  
  
    # Base case 
    if (low + 1 == high): 
        return 1
    else: 
  
        # Mid refers to ending index of 
        # opening bracket at index low 
        mid = endIndex[low] 
        if (mid == high): 
            return 2*(calcWeight(s, low + 1, 
            high-1, endIndex)) 
  
        else: 
            return calcWeight(s, low, 
            mid, endIndex) + calcWeight(s, 
            mid + 1, high, endIndex) 
  
  
if __name__ == "__main__": 
    string = "(()(()))"
    n = len(string) 
    endIndex = getClosingIndex(string) 
    print(calcWeight(string, 0, 
    n-1, endIndex))


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic; 
  
class GFG{
  
// HashMap to store the ending
// index of every opening bracket
static Dictionary endIndex = new Dictionary();
  
// Function to calculate and store
// the closing index of each opening
// bracket in the parenthesis
public static void getClosingIndex(string s)
{
    int n = s.Length;
  
    Stack st = new Stack();
  
    for(int i = 0; i < n; i++)
    {
        if (s[i] == ')') 
        {
              
            // If it's a closing bracket,
            // pop index of it's corresponding
            // opening bracket
            int startIndex = st.Pop();
  
            // Insert the index of opening
            // bracket and closing bracket
            // as key-value pair in the
            // hashmap
            endIndex.Add(startIndex, i);
        }
        else
        {
  
            // If it's an opening bracket,
            // push it's index into the stack
            st.Push(i);
        }
    }
}
  
// Function to return the weight of
// parenthesis
public static int calcWeight(string s, int low,
                                       int high)
{
  
    // Base case
    if (low + 1 == high)
    {
        return 1;
    }
    else 
    {
          
        // Mid refers to ending index of
        // opening bracket at index low
        int mid = endIndex[low];
        if (mid == high)
        {
            return 2 * calcWeight(s, low + 1,
                                    high - 1);
        }
        else
        {
            return calcWeight(s, low, mid) + 
                   calcWeight(s, mid + 1, high);
        }
    }
}
  
// Driver code
public static void Main(string[] args)
{
    string input = "(()(()))";
    int n = input.Length;
  
    // Update the closing Index
    getClosingIndex(input);
  
    Console.Write(calcWeight(input, 0, n - 1));
}
}
  
// This code is contributed by rutvik_56


输出:
6


时间复杂度: O(N)
辅助空间: O(N),其中N是字符串的长度。