Skip to content

Instantly share code, notes, and snippets.

@vignarajj
Created January 21, 2019 08:03
Show Gist options
  • Save vignarajj/a268e459ba9c3255b41695f266763611 to your computer and use it in GitHub Desktop.
Save vignarajj/a268e459ba9c3255b41695f266763611 to your computer and use it in GitHub Desktop.
To Generate the non-repeated characters of String. Given two integers X and Y, returns containing exactly X letters "A" and exactly Y letters "b". X defines maximum of character repetition.
public class NonRepeatCharacters {
public static void main(String[] args) {
System.out.println("Answer is " + NonRepeatString(2, 5, 3));
}
// n = Maximum number of repeation;
// x = 1st character with number of times.
// y -2nd character with number of times.
public static String NonRepeatString(int n, int X, int Y) {
String biggerString, smallerString;
int biggerCount, smallerCount;
if (n > X || n > Y) {
return "Invalid Solution";
}
if (X >= Y) {
biggerString = "A";
smallerString = "b";
biggerCount = X;
smallerCount = Y;
} else {
biggerString = "b";
smallerString = "A";
biggerCount = Y;
smallerCount = X;
}
// A > NB + N
// if (biggerCount > 2 * smallerCount + 2) {
if (biggerCount > ((n * smallerCount) + n)) {
return "Invalid Value Entry";
}
StringBuilder returnString = new StringBuilder();
do {
if (biggerCount == smallerCount + (n - 1)) {
returnString.append(biggerString);
biggerCount--;
} else if (biggerCount == smallerCount) {
returnString.append(biggerString);
biggerCount--;
returnString.append(smallerString);
smallerCount--;
} else {
int nFinal = 0;
if (n < biggerCount) {
nFinal = n;
} else {
nFinal = biggerCount;
}
for (int i = 0; i < nFinal; i++) {
returnString.append(biggerString);
}
biggerCount -= n;
if (smallerCount > 0) {
int sFinal = 0;
if(n<=smallerCount){
sFinal = n-1;
}else{
sFinal = smallerCount;
}
for (int j = 0; j <sFinal; j++) {
returnString.append(smallerString);
}
smallerCount -= n-1;
}
}
} while (biggerCount > 0);
return returnString.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment