October 07, 2019

Number of characters to be removed to make two string anagram

/**
 * Anagram solver
Number of characters to be removed to make two string anagram
 */
package com.steffi.samples;

/**
 * @author Konzern Technologies
 *
 */
public class Anagram {

private int ptr = 0;
private StringBuilder sb = null;

public Anagram(StringBuilder sb) {
this.sb = sb;
}

/**
* @param args
*/
public static void main(String[] args) {
String str1 = "RAMU";
String str2 = "RAMESHA";
char[] char1 = str1.toCharArray();
char[] char2 = str2.toCharArray();
StringBuilder sb = new StringBuilder();
Anagram anagram = new Anagram(sb);
String ans = (str1.length() < str2.length()) ? anagram.compute(char1, char2) : anagram.compute(char2, char1);
System.out.println("Anagram : "+ans);
System.out.println((str1.length()+str2.length())-(ans.length()*2));

}

private String compute(char[] charA, char[] charB) {
for (int i = 0; i < charB.length; i++) {
if (charA[ptr] == charB[i]) {
sb.append(charA[ptr]);
charB[i] =' ';
break;
}
}
ptr++;
if (ptr >= (charA.length)) {
return sb.toString();
} else {
return compute(charA, charB);
}
}



}


outputs

RAM
5


Inputs Strings RAMU & RAMESH
Anagram :RAM
Characters to remove 4

Inputs Strings RAMUS & RAMESH
Anagram :RAMS
Characters to remove 3

Inputs Strings ARGENTINA & BRAZIL
Anagram :RAI
Characters to remove 9

Inputs Strings KONZERN & AMADEUS
Anagram :E
Characters to remove 12


Inputs Strings VIJI & ELIZA
Anagram :I
Characters to remove 7

Inputs Strings BLACK & MAMBA
Anagram :AB
Characters to remove 6





Tik Toc Toe in python, two player game, playing with computer complete source code available soon...

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments