-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_pallindromic_subsequence_efficient.java
130 lines (120 loc) · 2.73 KB
/
longest_pallindromic_subsequence_efficient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
dp array is
1 1 1 1 3 5
0 1 1 1 3 3
0 0 1 1 1 1
0 0 0 1 1 1
0 0 0 0 1 1
0 0 0 0 0 1
after space efficient
1,1,1,1,1,1,
1,1,1,1,1,
1,1,1,1,
1,3,1,
3,3,
5, // final answer ... i have not printed it .. but you can do it by putting a condition while printing i.e. if(count+1==len)
//print(temp[i]) in every print statement;
*/
/**
*
* @author shivam
*/
public class longest_pallindromic_subsequence_efficient {
static int max(int a,int b)
{
return a>b?a:b;
}
public static void main(String[] args) {
String s= "abgdba";
int len=s.length();
int temp1[]=new int[len];
int temp2[]=new int[len-1];
int temp3[]=new int[len-2];
int i,j,count=1,flag=1,column;
for(i=0;i<len;i++)
{
temp1[i]=1;
System.out.print(temp1[i]+",");
}
System.out.println("");
for(i=0;i<len-1;i++)
{
if(s.charAt(i)==s.charAt(i+1)){
temp2[i]=2;
System.out.print(temp2[2]+",");
}
else{
temp2[i]=1;
System.out.print(temp2[i]+",");
}
}
System.out.println("");
flag=3;
count=2;
while(count<len)
{
if(flag==3)
{
column=count;
for(i=0;i<len-count && column<len;i++)
{
if(s.charAt(i)==s.charAt(column)){
temp3[i]=2+temp1[i+1];
System.out.print(temp3[i]+",");
}
else{
temp3[i]=max(temp2[i],temp2[i+1]);
System.out.print(temp3[i]+",");
}
column++;
}
System.out.println("");
}
if(flag==2)
{
column=count;
for(i=0;i<len-count && column<len;i++)
{
if(s.charAt(i)==s.charAt(column)){
temp2[i]=2+temp3[i+1];
System.out.print(temp2[i]+",");
}
else
temp2[i]=max(temp1[i],temp1[i+1]);{
System.out.print(temp2[i]+",");
}
column++;
}
System.out.println("");
}
if(flag==1)
{
column=count;
for(i=0;i<len-count && column<len;i++)
{
if(s.charAt(i)==s.charAt(column))
{
temp1[i]=2+temp2[i+1];
System.out.print(temp1[i]+",");
}
else{
temp1[i]=max(temp3[i],temp3[i+1]);
System.out.print(temp1[i]+",");
}
column++;
}
System.out.println("");
}
if(flag==3)
flag=1;
else
flag+=1;
count++;
}
}
}