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

📅  最后修改于: 2021-09-07 03:07:03             🧑  作者: 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)

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