📌  相关文章
📜  通过从二进制字符串中删除所有出现的 01 和 11 获得的最小字符串

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

给定一个二进制字符串S ,任务是通过删除所有出现的子字符串“01”“11”来找到可能的最小字符串。去除任何子后,将字符串的其余部分。

例子:

方法:解决问题的思路是观察以下情况:

  • 0111表示?1可以在‘?’ 处删除可以是10
  • 最后的字符串将始终采用1000…000…的形式

这个问题可以通过在从左到右处理给定字符串S 的同时维护一个 Stack 来解决。如果当前二进制数字为0 ,则将其添加到堆栈中,如果当前二进制数字为1 ,则从堆栈中移除顶部位。如果堆栈为空,则将当前位压入堆栈。请按照以下步骤解决问题:

  1. 初始化一个Stack来存储可能的最小字符串。
  2. [0, N – 1]范围内遍历给定字符串。
  3. 如果堆栈为空,则将当前二进制数字S[i] 压入堆栈。
  4. 如果堆栈不为空且当前位S[i]1,则从堆栈中删除顶部位。
  5. 如果当前元素S[i]0,则将其压入堆栈。
  6. 最后,从上到下附加堆栈中存在的所有元素,并将其打印为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find minimum
// length of the given string
void findMinLength(string s, int n)
{
    // Initialize a stack
    stack st;
 
    // Traverse the string
    for (int i = 0; i < n; i++) {
 
        // If the stack is empty
        if (st.empty())
 
            // Push the character
            st.push(s[i]);
 
        // If the character is 1
        else if (s[i] == '1')
 
            // Pop the top element
            st.pop();
 
        // Otherwise
        else
            // Push the character
            // to the stack
            st.push(s[i]);
    }
 
    // Initialize length
    int ans = 0;
 
    // Append the characters
    // from top to bottom
    vector finalStr;
 
    // Until Stack is empty
    while (!st.empty()) {
        ans++;
        finalStr.push_back(st.top());
        st.pop();
    }
 
    // Print the final string size
    cout << "Length = " << ans;
 
    // If length of the string is not 0
    if (ans != 0) {
 
        // Print the string
        cout << "\nString = ";
        for (int i = 0; i < ans; i++)
            cout << finalStr[i];
    }
}
 
// Driver Code
int main()
{
    // Given string
    string S = "101010";
 
    // String length
    int N = S.size();
 
    // Function call
    findMinLength(S, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find minimum
// length of the given string
static void findMinLength(String s, int n)
{
     
    // Initialize a stack
    Stack st = new Stack<>(); 
 
    // Traverse the string
    for(int i = 0; i < n; i++)
    {
         
        // If the stack is empty
        if (st.empty())
 
            // Push the character
            st.push(s.charAt(i));
 
        // If the character is 1
        else if (s.charAt(i) == '1')
 
            // Pop the top element
            st.pop();
 
        // Otherwise
        else
         
            // Push the character
            // to the stack
            st.push(s.charAt(i));
    }
 
    // Initialize length
    int ans = 0;
 
    // Append the characters
    // from top to bottom
    Vector finalStr = new Vector();
 
    // Until Stack is empty
    while (st.size() > 0)
    {
        ans++;
        finalStr.add(st.peek());
        st.pop();
    }
 
    // Print the final string size
    System.out.println("Length = " + ans);
 
    // If length of the string is not 0
    if (ans != 0)
    {
         
        // Print the string
        System.out.print("String = ");
         
        for(int i = 0; i < ans; i++)
            System.out.print(finalStr.get(i));
    }
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given string
    String S = "101010";
 
    // String length
    int N = S.length();
 
    // Function call
    findMinLength(S, N);
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Python3
# Python3 program for the above approach
 
from collections import deque
 
# Function to find minimum length
# of the given string
def findMinLength(s, n):
   
    # Initialize a stack
    st = deque()
     
    # Traverse the string from
    # left to right
    for i in range(n):
       
        # If the stack is empty,
        # push the character
        if (len(st) == 0):
            st.append(s[i])
         
        # If the character
        # is B, pop from stack
        elif (s[i] == '1'):
            st.pop()
         
        # Otherwise, push the
        # character to the stack
        else:
            st.append(s[i])
     
    # Stores resultant string
    ans = 0
    finalStr = []
    while (len(st) > 0):
        ans += 1
        finalStr.append(st[-1]);
        st.pop()
         
    # Print the final string size
    print("The final string size is: ", ans)
     
    # If length is not 0
    if (ans == 0):
        print("The final string is: EMPTY")
     
    # Print the string
    else:
        print("The final string is: ", *finalStr)
 
# Driver Code
if __name__ == '__main__':
   
    # Given string
    s = "0010110"
     
    # String length
    n = 7
     
    # Function Call
    findMinLength(s, n)


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find minimum
// length of the given string
static void findMinLength(String s, int n)
{
     
    // Initialize a stack
    Stack st = new Stack(); 
 
    // Traverse the string
    for(int i = 0; i < n; i++)
    {
         
        // If the stack is empty
        if (st.Count == 0)
         
            // Push the character
            st.Push(s[i]);
 
        // If the character is 1
        else if (s[i] == '1')
 
            // Pop the top element
            st.Pop();
 
        // Otherwise
        else
         
            // Push the character
            // to the stack
            st.Push(s[i]);
    }
 
    // Initialize length
    int ans = 0;
 
    // Append the characters
    // from top to bottom
    List finalStr = new List();
 
    // Until Stack is empty
    while (st.Count > 0)
    {
        ans++;
        finalStr.Add(st.Peek());
        st.Pop();
    }
 
    // Print the readonly string size
    Console.WriteLine("Length = " + ans);
 
    // If length of the string is not 0
    if (ans != 0)
    {
         
        // Print the string
        Console.Write("String = ");
         
        for(int i = 0; i < ans; i++)
            Console.Write(finalStr[i]);
    }
}
 
// Driver Code
public static void Main(String []args)
{
     
    // Given string
    String S = "101010";
 
    // String length
    int N = S.Length;
 
    // Function call
    findMinLength(S, N);
}
}
 
// This code is contributed by Amit Katiyar


输出:
Length = 2
String = 01










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

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