这是查找美丽子字符串的程序。它是完全优化的代码,使用动态编程具有较低的复杂性。
static String LCSubStr(String X,String Y, int m, int n)// Longest Common substring
{
int LCSarr[][]=new int[m+1][n+1];
int max = 0;
int max_index=0;
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
LCSarr[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))//if char matches
{
LCSarr[i][j] = LCSarr[i-1][j-1] + 1;
if(max < LCSarr[i][j])
{
max=LCSarr[i][j];
max_index=i; //Index points at which last char matched
}
}
else LCSarr[i][j] = 0;
}
}
return (X.substring(max_index-max,max_index));
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter String 1: ");
String str=new String(sc.nextLine());
str=str.toLowerCase();
String temp2="";//string with no duplicates
HashMap<Integer,Character> tc = new HashMap<Integer,Character>();//create a hashmap to store the char's
char [] charArray = str.toCharArray();
for (Character c : charArray)//for each char
{
if (!tc.containsValue(c))//if the char is not already in the hashmap
{
temp2=temp2+c.toString();//add the char to the output string
tc.put(c.hashCode(),c);//and add the char to the hashmap
}
}
System.out.print("\nBeatiful substring of given String is: ");
System.out.println(LCSubStr(str,temp2,str.length(),temp2.length()));//Find Longest common substring which gives us actually beautiful string
}