If ans string is empty or its last character does not match with the current character then append this character to the string
if ( ans . isEmpty ( ) || ans . charAt ( ans . length ( ) - 1 ) != S . charAt ( i ) ) ans += S . charAt ( i ) ;