📌  相关文章
📜  使用堆栈从字符串删除所有重复的相邻字符

📅  最后修改于: 2021-05-06 23:40:34             🧑  作者: Mango

给定字符串str ,任务是从给定字符串删除所有重复的相邻字符。

例子:

递归方法:请参阅“递归删除所有相邻重复项”一文,以递归解决此问题。
时间复杂度: O(N)
辅助空间: O(N)

字符串函数系的方法:请参阅本文删除第一相邻对类似字符,直到能够解决使用内置函数pop_back()和背面字符串()方法这一问题。

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

基于堆栈的方法:使用堆栈可以使用LIFO的属性可以解决该问题。这个想法是从左到右遍历字符串,并检查堆栈是否为空或堆栈的顶部元素是否不等于str的当前字符,然后将当前字符推入堆栈。否则,从堆栈顶部弹出元素。请按照以下步骤解决问题:

  1. 创建一个堆栈st,以删除str中相邻的重复字符。
  2. 遍历字符串str并检查堆栈是否为空或堆栈的顶部元素是否不等于当前字符。如果发现是真的,则将当前字符推入st
  3. 否则,从堆栈顶部弹出元素。
  4. 最后,打印堆栈中所有剩余的元素。
C++
// C++ program to implement 
// the above approach 
#include 
using namespace std;
  
// Function to remove adjacent 
// duplicate elements 
string ShortenString(string str1)
{
      
    // Store the string without 
    // duplicate elements 
    stack st; 
      
    // Store the index of str 
    int i = 0;
      
    // Traverse the string str
    while (i < str1.length())
    {
          
        // Checks if stack is empty or top of the 
        // stack is not equal to current character 
        if (st.empty() || str1[i] != st.top())
        {
            st.push(str1[i]);
            i++;
        }
              
        // If top element of the stack is 
        // equal to the current character 
        else
        {
            st.pop(); 
            i++;
        } 
    }
      
    // If stack is empty 
    if (st.empty())
    {
        return ("Empty String");
    }
          
    // If stack is not Empty 
    else
    {
        string short_string = ""; 
        while (!st.empty())
        {
            short_string = st.top() + 
                           short_string;
            st.pop();
        }
        return (short_string);
    }
}
  
// Driver Code
int main()
{
    string str1 ="azzxzy";
      
    cout << ShortenString(str1); 
  
    return 0;
}
  
// This code is contributed by divyeshrabadiya07


Java
// Java program to implement 
// the above approach 
import java.util.*;
class GFG{
  
// Function to remove adjacent 
// duplicate elements 
static String ShortenString(String str1)
{
  // Store the String without 
  // duplicate elements 
  Stack st = 
        new Stack(); 
  
  // Store the index of str 
  int i = 0;
  
  // Traverse the String str
  while (i < str1.length())
  {
    // Checks if stack is empty 
    // or top of the stack is not
    // equal to current character 
    if (st.isEmpty() || 
        str1.charAt(i) != st.peek())
    {
      st.add(str1.charAt(i));
      i++;
    }
  
    // If top element of the stack is 
    // equal to the current character 
    else
    {
      st.pop(); 
      i++;
    } 
  }
  
  // If stack is empty 
  if (st.isEmpty())
  {
    return ("Empty String");
  }
  
  // If stack is not Empty 
  else
  {
    String short_String = ""; 
    while (!st.isEmpty())
    {
      short_String = st.peek() + 
                     short_String;
      st.pop();
    }
    return (short_String);
  }
}
  
// Driver Code
public static void main(String[] args)
{
  String str1 ="azzxzy";
  System.out.print(ShortenString(str1)); 
  
}
}
  
// This code is contributed by Rajput-Ji


Python3
# Python3 program to implement
# the above approach
  
# Function to remove adjacent
# duplicate elements
def ShortenString(str1):
      
    # Store the string without 
    # duplicate elements
    st = []
      
    # Store the index of str
    i = 0
      
    # Traverse the string str
    while i < len(str1):
          
        # Checks if stack is empty or top of the
        # stack is not equal to current character
        if len(st)== 0 or str1[i] != st[-1]:
            st.append(str1[i])
            i += 1
              
        # If top element of the stack is 
        # equal to the current character
        else:
            st.pop()
            i += 1
              
    # If stack is empty
    if len(st)== 0:
        return("Empty String")
          
    # If stack is not Empty
    else:
        short_string = ""
        for i in st:
            short_string += str(i)
        return(short_string)
        
# Driver Code
if __name__ == "__main__": 
    str1 ="azzxzy"
    print(ShortenString(str1))


C#
// C# program to implement 
// the above approach 
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to remove adjacent 
// duplicate elements 
static String ShortenString(String str1)
{
      
    // Store the String without 
    // duplicate elements 
    Stack st = new Stack(); 
      
    // Store the index of str 
    int i = 0;
      
    // Traverse the String str
    while (i < str1.Length)
    {
          
        // Checks if stack is empty 
        // or top of the stack is not
        // equal to current character 
        if (st.Count == 0 || (st.Count != 0 &&
             str1[i] != st.Peek()))
        {
            st.Push(str1[i]);
            i++;
        }
      
        // If top element of the stack is 
        // equal to the current character 
        else
        {
            if (st.Count != 0)
                st.Pop(); 
                  
            i++;
        } 
    }
      
    // If stack is empty 
    if (st.Count == 0)
    {
        return ("Empty String");
    }
      
    // If stack is not Empty 
    else
    {
        String short_String = ""; 
          
        while (st.Count != 0)
        {
            short_String = st.Peek() + 
                           short_String;
            st.Pop();
        }
        return (short_String);
    }
}
  
// Driver Code
public static void Main(String[] args)
{
    String str1 ="azzxzy";
      
    Console.Write(ShortenString(str1)); 
}
}
  
// This code is contributed by Amit Katiyar


输出:
axzy

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