📌  相关文章
📜  从给定的有效括号序列中找到长度为K的有效括号序列

📅  最后修改于: 2021-04-21 20:55:43             🧑  作者: Mango

给定字符串S的有效括号长度为N ,偶数为K ,任务是找到长度为K的有效括号序列,该长度也是给定字符串。

注意:可以有多个有效序列,可以打印其中任何一个。

例子:

天真的方法:想法是生成给定字符串长度K的所有可能的子序列,并打印具有有效括号序列的任何字符串。
时间复杂度: O(2 N )
辅助空间: O(K)

高效方法:可以使用堆栈来优化上述方法。这个想法是遍历给定的字符串,当遇到一个开放的括号字符时,将其压入其他堆栈,然后从中弹出一个字符。相应地,每次弹出一个字符都增加计数器。请按照以下步骤解决问题:

  1. 创建一个堆栈和一个布尔数组,将其初始化为false
  2. 遍历给定的字符串,如果遇到开括号,则将该索引推入堆栈。
  3. 否则,如果遇到右括号:
    • 从堆栈中弹出顶部元素
    • 计数器加2
    • 将弹出的标记和当前索引标记为true。
  4. 如果计数器超过K ,则终止。
  5. 遍历后,将所有字符从左到右附加在一起,标记为true。打印形成的结果字符串。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
#define ll long long
using namespace std;
 
// Function to find the subsequence
// of length K forming valid sequence
string findString(string s, int k)
{
    int n = s.length();
 
    // Stores the resultant string
    string ans = "";
    stack st;
 
    // Check whether character at
    // index i is visited or not
    vector vis(n, false);
    int count = 0;
 
    // Traverse the string
    for (int i = 0; i < n; ++i) {
 
        // Push index of open bracket
        if (s[i] == '(') {
            st.push(i);
        }
 
        // Pop and mark visited
        if (count < k && s[i] == ')') {
 
            vis[st.top()] = 1;
            st.pop();
            vis[i] = true;
 
            // Increment count by 2
            count += 2;
        }
    }
 
    // Append the characters and create
    // the resultant string
    for (int i = 0; i < n; ++i) {
 
        if (vis[i] == true) {
            ans += s[i];
        }
    }
 
    // Return the resultant string
    return ans;
}
 
// Driver Code
int main()
{
    string s = "()()()";
    int K = 2;
 
    // Function Call
    cout << findString(s, K);
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the subsequence
// of length K forming valid sequence
static String findString(String s, int k)
{
    int n = s.length();
 
    // Stores the resultant String
    String ans = " ";
    Stack st = new Stack<>();
 
    // Check whether character at
    // index i is visited or not
    boolean []vis = new boolean[n];
     
    // Vector vis(n, false);
    int count = 0;
 
    // Traverse the String
    for(int i = 0; i < n; ++i)
    {
         
        // Push index of open bracket
        if (s.charAt(i) == '(')
        {
            st.add(i);
        }
 
        // Pop and mark visited
        if (count < k && s.charAt(i) == ')')
        {
            vis[st.peek()] = true;
            st.pop();
            vis[i] = true;
 
            // Increment count by 2
            count += 2;
        }
    }
 
    // Append the characters and create
    // the resultant String
    for(int i = 0; i < n; ++i)
    {
        if (vis[i] == true)
        {
            ans += s.charAt(i);
        }
    }
 
    // Return the resultant String
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    String s = "()()()";
    int K = 2;
 
    // Function call
    System.out.print(findString(s, K));
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for the above approach
 
# Function to find the subsequence
# of length K forming valid sequence
def findString(s, k):
     
    n = len(s)
 
    # Stores the resultant string
    ans = ""
    st = []
 
    # Check whether character at
    # index i is visited or not
    vis = [False] * n
    count = 0
 
    # Traverse the string
    for i in range(n):
 
        # Push index of open bracket
        if (s[i] == '('):
            st.append(i)
 
        # Pop and mark visited
        if (count < k and s[i] == ')'):
            vis[st[-1]] = 1
            del st[-1]
            vis[i] = True
 
            # Increment count by 2
            count += 2
 
    # Append the characters and create
    # the resultant string
    for i in range(n):
        if (vis[i] == True):
            ans += s[i]
             
    # Return the resultant string
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    s = "()()()"
    K = 2
 
    # Function call
    print(findString(s, K))
 
# This code is contributed by mohit kumar 29


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the
// subsequence of length
// K forming valid sequence
static String findString(String s,
                         int k)
{
  int n = s.Length;
 
  // Stores the resultant String
  String ans = " ";
  Stack st = new Stack();
 
  // Check whether character at
  // index i is visited or not
  bool []vis = new bool[n];
 
  // List vis(n, false);
  int count = 0;
 
  // Traverse the String
  for(int i = 0; i < n; ++i)
  {
    // Push index of open bracket
    if (s[i] == '(')
    {
      st.Push(i);
    }
 
    // Pop and mark visited
    if (count < k && s[i] == ')')
    {
      vis[st.Peek()] = true;
      st.Pop();
      vis[i] = true;
 
      // Increment count by 2
      count += 2;
    }
  }
 
  // Append the characters and create
  // the resultant String
  for(int i = 0; i < n; ++i)
  {
    if (vis[i] == true)
    {
      ans += s[i];
    }
  }
 
  // Return the resultant String
  return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
  String s = "()()()";
  int K = 2;
 
  // Function call
  Console.Write(findString(s, K));
}
}
 
// This code is contributed by Princi Singh


输出:
()




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