Super Reduced String

  • + 16 comments

    Thanks for that i = 0 :) Had basically the same code, but I couldn't think of an easy solution to go back to the beginning of the string again after deleting a pair of letters, even if it was that easy...

    I used StringBuffer instead of String. Isn't it more efficient, cause less objects are created? I'm really not sure about that, some feedback would be appreciated. Here my code:

    public static void main(String[] args) {
            Scanner stdin = new Scanner(System.in);
            StringBuffer s = new StringBuffer(stdin.nextLine());
            for(int i = 1; i < s.length(); i++) {
                if(s.charAt(i) == s.charAt(i-1)) {
                    s.delete(i-1, i+1);
                    i = 0;
                }
            }
            if(s.length() == 0) System.out.println("Empty String");
            else System.out.println(s);
        }
    }