📜  在字符串括号中找到一个相等的点

📅  最后修改于: 2022-05-13 01:57:07.177000             🧑  作者: Mango

在字符串括号中找到一个相等的点

给定字符串括号,任务是找到一个索引 k,它决定左括号的数量等于右括号的数量。
字符串必须仅由左括号和右括号组成,即“(”和“)”。

等点是一个索引,使得它之前的左括号的数量等于它之前和之后的右括号的数量。

例子:

Input : str = "(())))("
Output:   4
After index 4, string splits into (())
and ))(. Number of opening brackets in the 
first part is equal to number of closing 
brackets in the second part.

Input : str = "))"
Output: 2
As after 2nd position i.e. )) and "empty"
string will be split into these two parts:
So, in this number of opening brackets i.e.
0 in the first part is equal to number of 
closing brackets in the second part i.e. 
also 0.

无标题

询问:亚马逊

方法一:

  1. 存储字符串中出现的左括号的数量,直到每个索引,它必须从起始索引开始。
  2. 同样,将字符串中出现的右括号的数量存储到每个索引,但应该从最后一个索引开始。
  3. 检查是否有任何索引具有相同的左括号和右括号值。
C++
// C++ program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
#include
using namespace std;
 
// Function to find an equal index
int findIndex(string str)
{
    int len = str.length();
    int open[len+1], close[len+1];
    int index = -1;
    memset(open, 0, sizeof (open));
    memset(close, 0, sizeof (close));
 
    open[0] = 0;
    close[len] = 0;
    if (str[0]=='(')
        open[1] = 1;
    if (str[len-1] == ')')
        close[len-1] = 1;
 
    // Store the number of opening brackets
    // at each index
    for (int i = 1; i < len; i++)
    {
        if ( str[i] == '(' )
            open[i+1] = open[i] + 1;
        else
            open[i+1] = open[i];
    }
 
    // Store the number of closing brackets
    // at each index
    for (int i = len-2; i >= 0; i--)
    {
        if ( str[i] == ')' )
            close[i] = close[i+1] + 1;
        else
            close[i] = close[i+1];
    }
 
    // check if there is no opening or closing
    // brackets
    if (open[len] == 0)
        return len;
    if (close[0] == 0)
        return 0;
 
    // check if there is any index at which
    // both brackets are equal
    for (int i=0; i<=len; i++)
        if (open[i] == close[i])
            index = i;
 
    return index;
}
 
// Driver code
int main()
{
    string str = "(()))(()()())))";
    cout << findIndex(str);
    return 0;
}


Java
// Java program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
 
public class GFG
{
    // Method to find an equal index
    static int findIndex(String str)
    {
        int len = str.length();
        int open[] = new int[len+1];
        int    close[] = new int[len+1];
        int index = -1;
      
        open[0] = 0;
        close[len] = 0;
        if (str.charAt(0)=='(')
            open[1] = 1;
        if (str.charAt(len-1) == ')')
            close[len-1] = 1;
      
        // Store the number of opening brackets
        // at each index
        for (int i = 1; i < len; i++)
        {
            if ( str.charAt(i) == '(' )
                open[i+1] = open[i] + 1;
            else
                open[i+1] = open[i];
        }
      
        // Store the number of closing brackets
        // at each index
        for (int i = len-2; i >= 0; i--)
        {
            if ( str.charAt(i) == ')' )
                close[i] = close[i+1] + 1;
            else
                close[i] = close[i+1];
        }
      
        // check if there is no opening or closing
        // brackets
        if (open[len] == 0)
            return len;
        if (close[0] == 0)
            return 0;
     
        // check if there is any index at which
        // both brackets are equal
        for (int i=0; i<=len; i++)
            if (open[i] == close[i])
                index = i;
      
        return index;
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        String str = "(()))(()()())))";
        System.out.println(findIndex(str));
    }
}


Python3
# Method to find an equal index
def findIndex(str):
    l = len(str)
    open = [0] * (l + 1)
    close = [0] * (l + 1)
    index = -1
     
    open[0] = 0
    close[l] = 0
    if (str[0]=='('):
        open[1] = 1
    if (str[l - 1] == ')'):
        close[l - 1] = 1
     
    # Store the number of
    # opening brackets
    # at each index
    for i in range(1, l):
        if (str[i] == '('):
            open[i + 1] = open[i] + 1
        else:
            open[i + 1] = open[i]
     
    # Store the number
    # of closing brackets
    # at each index
    for i in range(l - 2, -1, -1):
        if ( str[i] == ')'):
            close[i] = close[i + 1] + 1
        else:
            close[i] = close[i + 1]
     
    # check if there is no
    # opening or closing brackets
    if (open[l] == 0):
        return len
    if (close[0] == 0):
        return 0
     
    # check if there is any
    # index at which both
    # brackets are equal
    for i in range(l + 1):
        if (open[i] == close[i]):
            index = i
     
    return index
     
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
 
# This code is contributed
# by ChitraNayal


C#
// C# program to find an index
// k which decides the number
// of opening brackets is equal
// to the number of closing brackets
using System;
 
class GFG
{
// Method to find an equal index
static int findIndex(string str)
{
    int len = str.Length;
    int[] open = new int[len + 1];
    int[] close = new int[len + 1];
    int index = -1;
 
    open[0] = 0;
    close[len] = 0;
    if (str[0] == '(')
        open[1] = 1;
    if (str[len - 1] == ')')
        close[len - 1] = 1;
 
    // Store the number of
    // opening brackets
    // at each index
    for (int i = 1; i < len; i++)
    {
        if (str[i] == '(')
            open[i + 1] = open[i] + 1;
        else
            open[i + 1] = open[i];
    }
 
    // Store the number
    // of closing brackets
    // at each index
    for (int i = len - 2; i >= 0; i--)
    {
        if (str[i] == ')')
            close[i] = close[i + 1] + 1;
        else
            close[i] = close[i + 1];
    }
 
    // check if there is no
    // opening or closing
    // brackets
    if (open[len] == 0)
        return len;
    if (close[0] == 0)
        return 0;
 
    // check if there is any
    // index at which both
    // brackets are equal
    for (int i = 0; i <= len; i++)
        if (open[i] == close[i])
            index = i;
 
    return index;
}
 
// Driver Code
public static void Main()
{
    string str = "(()))(()()())))";
    Console.Write(findIndex(str));
}
}
 
// This code is contributed
// by ChitraNayal


PHP
= 0; $i--)
    {
        if ($str[$i] == ')')
        $close[$i] = $close[$i + 1] + 1;
        else
        $close[$i] = $close[$i + 1];
    }
     
    // check if there is no
    // opening or closing
    // brackets
    if ($open[$len] == 0)
        return $len;
    if ($close[0] == 0)
        return 0;
     
    // check if there is any
    // index at which both
    // brackets are equal
    for ($i = 0; $i <= $len; $i++)
        if ($open[$i] == $close[$i])
            $index = $i;
     
    return $index;
}
     
// Driver Code
$str = "(()))(()()())))";
echo (findIndex($str));
 
// This code is contributed
// by ChitraNayal
?>


Javascript


C++
// C++ program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
#include 
using namespace std;
 
// Function to find an equal index
int findIndex(string str)
{
    // STL to count occurences of ')'
    int cnt_close = count(str.begin(), str.end(), ')');
    for (int i = 0; str[i] != '\0'; i++)
        if (cnt_close == i)
            return i;
    // If no opening brackets
    return str.size();
}
 
// Driver code
int main()
{
    string str = "(()))(()()())))";
    cout << findIndex(str);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java
// Java program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
 
public class GFG {
    // Method to find an equal index
    static int findIndex(String str)
    {
        int len = str.length();
        int cnt_close = 0;
        for (int i = 0; i < len; i++)
            if (str.charAt(i) == ')')
                cnt_close++;
        for (int i = 0; i < len; i++)
            if (cnt_close == i)
                return i;
        // If no opening brackets
        return len;
    }
 
    // Driver Method
    public static void main(String[] args)
    {
        String str = "(()))(()()())))";
        System.out.println(findIndex(str));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3
# Method to find an equal index
def findIndex(str):
    cnt_close = 0
    l = len(str)
    for i in range(1, l):
        if(str[i] == ')'):
            cnt_close = cnt_close + 1
 
    for i in range(1, l):
        if(cnt_close == i):
            return i
    # If no opening brackets
    return l
 
 
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
 
# This code is contributed by Aditya Kumar (adityakumar129)


Javascript


PHP


输出:

9

时间复杂度: O(n)

方法二:

  1. 计算字符串中右括号的总数并存储在变量中,比如说cnt_close。
  2. 所以开括号的数量是字符串的长度——闭括号的数量。
  3. 再次遍历字符串,但现在保留字符串中开括号的数量,比如说cnt_open。
  4. 现在在遍历时,让索引为 i,因此在该索引为 i+1-cnt_open 之前,闭合括号的计数。
  5. 因此,我们可以检查什么索引,第一部分的开括号计数等于第二部分的闭括号计数。
  6. 方程变为cnt_close-(i+1-cnt_open) = cnt_open,我们必须找到i。
  7. 在评估上述等式后,我们可以看到 cnt_open 在两边都被取消了,所以不需要。

C++

// C++ program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
#include 
using namespace std;
 
// Function to find an equal index
int findIndex(string str)
{
    // STL to count occurences of ')'
    int cnt_close = count(str.begin(), str.end(), ')');
    for (int i = 0; str[i] != '\0'; i++)
        if (cnt_close == i)
            return i;
    // If no opening brackets
    return str.size();
}
 
// Driver code
int main()
{
    string str = "(()))(()()())))";
    cout << findIndex(str);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java

// Java program to find an index k which
// decides the number of opening brackets
// is equal to the number of closing brackets
 
public class GFG {
    // Method to find an equal index
    static int findIndex(String str)
    {
        int len = str.length();
        int cnt_close = 0;
        for (int i = 0; i < len; i++)
            if (str.charAt(i) == ')')
                cnt_close++;
        for (int i = 0; i < len; i++)
            if (cnt_close == i)
                return i;
        // If no opening brackets
        return len;
    }
 
    // Driver Method
    public static void main(String[] args)
    {
        String str = "(()))(()()())))";
        System.out.println(findIndex(str));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Python3

# Method to find an equal index
def findIndex(str):
    cnt_close = 0
    l = len(str)
    for i in range(1, l):
        if(str[i] == ')'):
            cnt_close = cnt_close + 1
 
    for i in range(1, l):
        if(cnt_close == i):
            return i
    # If no opening brackets
    return l
 
 
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
 
# This code is contributed by Aditya Kumar (adityakumar129)

Javascript


PHP


Output : 9

时间复杂度: O(n)

空间复杂度: O(1)