In: Computer Science
public int static mirroringIt(String str){
return n;
}
implement this function so its takes ONE string and remove the characters so it becomes a mirrored word.
example:
Input: qswwbi
Output: 4
remove q s b i
"wow" is a mirror word.
output : 0
Input : "if"
output : 1
remove either I or f because it's two words.
don't use 3rd parties library or java.util.
The java method for the problem is provided below, please comment if any doubts:
Note: The whole Java code is provided, the required function in the code is highlighted
public class Mirror {
public static int mirroringIt(String str)
{
//find the length of the input string
int len = str.length();
//to store the combination of strings
int List[][] = new int[len][len];
//store the single letters, its always mirrors
for (int itr = 0; itr < len; itr++)
List[itr][itr] = 1;
//find the longest substring of the string
//that is mirror to each other
for (int sub = 2; sub <= len; sub++)
{
for (int itr = 0; itr < len - sub + 1; itr++)
{
int k = itr + sub - 1;
if (str.charAt(itr) ==
str.charAt(k) && sub == 2)
List[itr][k] = 2;
else if (str.charAt(itr) ==
str.charAt(k))
List[itr][k] = List[itr + 1][k - 1] + 2;
else
List[itr][k] = Integer.max(List[itr][k - 1],
List[itr + 1][k]);
}
}
//return the number of letters to be removed
return (len-List[0][len - 1]);
}
//The main function to test the function
public static void main(String[] args)
{
String str = "qswwbi";
System.out.println(str +": "+mirroringIt(str));
str= "if";
System.out.println(str +": "+mirroringIt(str));
str= "wow";
System.out.println(str +": "+mirroringIt(str));
}
}
Output: