Skip to content

Instantly share code, notes, and snippets.

@cyberpirate92
Last active November 14, 2018 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyberpirate92/4c59f8d3ec540003a1afe76700cc3f54 to your computer and use it in GitHub Desktop.
Save cyberpirate92/4c59f8d3ec540003a1afe76700cc3f54 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.io.*;
import java.math.*;
public class RepeatingEvenString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inputString = in.nextLine();
String result = removeEvenRepeatedCharacters(inputString);
System.out.println(result);
}
public static String removeEvenRepeatedCharacters(String string) {
// if string length is less than 2, nothing needs to be done
if (string.length() < 2) {
return string;
}
// flag to denote if a change has been made
boolean changed;
do {
int charIndex = 0;
char currentChar = string.charAt(charIndex);
changed = false;
String temp = "";
for (int i=1; i<string.length(); i++) {
if (string.charAt(i) != currentChar) {
if ((i - charIndex) % 2 != 0) {
for(int j=charIndex; j<i; j++) {
temp += string.charAt(j);
}
}
else {
changed = true;
}
charIndex = i;
currentChar = string.charAt(charIndex);
}
// corner case involving the last character in the string
else if (string.charAt(i) == currentChar && i == string.length()-1 && (charIndex - i - 1)%2 != 0) {
for (int j=charIndex; j<=i; j++) {
temp += string.charAt(j);
}
}
}
// temp contains the resulting string after even repeating characters are removed in this iteration
string = temp;
if (string.length() < 2) break;
}while(changed); // if the string is changed, there is possibility of even repeating characters forming again
return string;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment