Delete consecutive same words in a sequence | Java implementation of above method ; Method to find the size of manipulated sequence ; Start traversing the sequence ; Push the current string if the stack is empty ; compare the current string with stack top if equal , pop the top ; Otherwise push the current string ; Return stack size ; Driver method
import java . util . Stack ; import java . util . Vector ; class Test { static int removeConsecutiveSame ( Vector < String > v ) { Stack < String > st = new Stack < > ( ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( st . empty ( ) ) st . push ( v . get ( i ) ) ; else { String str = st . peek ( ) ; if ( str . equals ( v . get ( i ) ) ) st . pop ( ) ; else st . push ( v . get ( i ) ) ; } } return st . size ( ) ; } public static void main ( String [ ] args ) { Vector < String > v = new Vector < > ( ) ; v . addElement ( " ab " ) ; v . addElement ( " aa " ) ; v . addElement ( " aa " ) ; v . addElement ( " bcd " ) ; v . addElement ( " ab " ) ; System . out . println ( removeConsecutiveSame ( v ) ) ; } }