[Timus] 1654 Cipher Message

Problem statement is here: http://acm.timus.ru/problem.aspx?space=1&num=1654

This problem can be easily solved by using stack. Keep pushing into stack until you see the current character equal to the top of the string, in that case pop the stack.

 

public void solve(int testNumber, InputReader in, OutputWriter out) {
            String input = in.nextString();
            Stack<Character> stk = new Stack<>();

            for (int i = 0; i < input.length(); i++) {
                char curr = input.charAt(i);
                if (stk.empty() || !stk.peek()
                        .equals(curr)) {
                    stk.push(curr);
                } else {
                    stk.pop();
                }
            }

            for (int i = 0; i < stk.size(); i++) {
                out.print(stk.get(i));
            }
        }

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.