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

📅  最后修改于: 2021-09-07 05:25:55             🧑  作者: 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] 权重的两倍
  • 如果右括号在开始和结束之间的某个位置,比如中间,那么根据约束号。 2,括号总权重将是字符串[start, mid]的权重和字符串[mid+1, end] 的权重
  • 我们递归的基本情况是当字符串只有两个括号时,它们的权重为 1,因为它们本质上是有效的。
  • 现在,问题是我们如何找到左括号对应的右括号的索引。这个想法类似于有效括号检查。我们将使用堆栈数据结构来检查和存储 HashMap 中相应左括号的右括号索引。
  • 执行以下步骤:
    • 遍历字符串。
    • 如果字符是左括号,则将其索引推入Stack
    • 如果它是一个括号,则从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 是字符串的长度。

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