Advertisement
josebaperu

Untitled

Oct 3rd, 2021
1,110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. package pkg;
  2.  
  3. import java.util.Iterator;
  4. import java.util.Stack;
  5.  
  6. public class RemoveToken {
  7.     public static void main(String[] args) {
  8.         final String s1 = "a#aayf#c#";
  9.         final String s2 = "aa#ayy#k#pp##";
  10.  
  11.         System.out.println(backSpaceString(s1,s2));
  12.     }
  13.     static int backSpaceString(final String s1, final String s2){
  14.         return reduceStr(s2).equals(reduceStr(s1))? 1: 0;
  15.     }
  16.  
  17.     static String reduceStr(final String str) {
  18.         final Stack<Character> stringStack = new Stack<>();
  19.         final Stack<Character> hashStack = new Stack<>();
  20.         final Stack<Character> resultStack = new Stack<>();
  21.  
  22.         for( char c : str.toCharArray()){
  23.             stringStack.push(c);
  24.         }
  25.         if (!stringStack.contains('#')){
  26.             return str;
  27.         }
  28.  
  29.         boolean keepRunning = true;
  30.         while(keepRunning){
  31.             if(stringStack.isEmpty() && hashStack.isEmpty()) {
  32.                 keepRunning = false;
  33.             }
  34.  
  35.             if(!stringStack.isEmpty() && stringStack.peek() != '#'){
  36.                 resultStack.push(stringStack.pop());
  37.             }
  38.             if(!stringStack.isEmpty() && stringStack.peek() == '#'){
  39.                 hashStack.push(stringStack.pop());
  40.             }
  41.             if(!resultStack.isEmpty() && !hashStack.isEmpty() && resultStack.peek() != '#'){
  42.                 hashStack.pop();
  43.                 resultStack.pop();
  44.             }
  45.  
  46.         }
  47.         final Iterator<Character> it = resultStack.iterator();
  48.         final StringBuilder sb = new StringBuilder();
  49.         while(it.hasNext()){
  50.             sb.append(it.next());
  51.         }
  52.         return sb.reverse().toString();
  53.     }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement