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

📅  最后修改于: 2021-09-07 04:52:50             🧑  作者: Mango

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

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

例子:

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

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

  1. 创建一个堆栈和布尔数组,初始化为false
  2. 遍历给定的字符串,如果遇到左括号,则将该索引压入堆栈。
  3. 否则,如果遇到右大括号:
    • 弹出栈顶元素
    • 将计数器增加2
    • 将弹出的和当前的索引标记为真。
  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


Javascript


输出:
()

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

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