You are given a binary string, (string which contains 0's and 1's), You have to perform several operations on this string, in one operation choose a non-empty even length substring containing only 0's or only 1's and remove it from the string.
Your goal is to minimize the final length of the string after performing several operations.It is possible that the final string may become empty, in that case print "KHALI" without quotes.
And it can be proved that there is always an unique string with minimal length after performing the operations.
Example:
Input: 101001
Output: 10
Approach
Java
public class IhateEvenSubarrays {public static void main(String args[]) {StringBuilder sb = new StringBuilder();char bits[] = "101001".toCharArray();char bits_stack[] = new char[bits.length];int stack_pointer = 0;for (int i = 0; i < bits.length; i++) {switch (stack_pointer) {case 0:bits_stack[0] = bits[i];stack_pointer = 1;break;default:if (bits_stack[stack_pointer - 1] == bits[i]) {bits_stack[--stack_pointer] = '\0';} else {bits_stack[stack_pointer++] = bits[i];}}}sb.append(((stack_pointer == 0) ? "KHALI" : new String(bits_stack).substring(0, stack_pointer)) + "\n");System.out.println(sb.toString());}}
No comments:
Post a Comment