题目
方法一:利用栈做匹配
class Solution { public String removeDuplicates ( String s) { Deque < Character > deque = new LinkedList < > ( ) ; StringBuffer str = new StringBuffer ( ) ; for ( int i = 0 ; i < s. length ( ) ; i++ ) { if ( ! deque. isEmpty ( ) && deque. peek ( ) == s. charAt ( i) ) deque. pop ( ) ; else deque. push ( s. charAt ( i) ) ; } while ( ! deque. isEmpty ( ) ) { str. append ( deque. pop ( ) ) ; } return str. reverse ( ) . toString ( ) ; }
}
方法二:消消乐
class Solution { public String removeDuplicates ( String s) { StringBuffer str = new StringBuffer ( s) ; for ( int i = 0 ; i < str. length ( ) ; i++ ) { if ( i> 0 && str. charAt ( i) == str. charAt ( i- 1 ) ) { str. delete ( i- 1 , i+ 1 ) ; i = i- 2 ; } } return str. toString ( ) ; }
}