File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Dynamic Programming/Longest Palindrome substring Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ string longestPalindrome (string s) {
4+ int n = s.length ();
5+ bool dp[n][n];
6+
7+ int ans = 1 ;
8+ int st = 0 ;
9+
10+ // /fill all substring of length 1
11+ for (int i=0 ; i<n; i++){
12+ dp[i][i] = true ;
13+ }
14+
15+ // /fill all substring of length 2
16+ for (int i=0 ; i<n-1 ; i++){
17+ if (s[i] == s[i+1 ]){
18+ ans = 2 ;
19+ dp[i][i+1 ] = true ;
20+ st = i;
21+ }
22+ else {
23+ dp[i][i+1 ] = false ;
24+ }
25+ }
26+
27+ // dp[i][j] means start at i and end at j...
28+ // /fill the rest of the table
29+ for (int l=3 ; l<=n; l++){ // for substring of length 3 and more...
30+ for (int i=0 ; i<=n-l; i++){ // n-l is the max index where index of //particular substring of length l end
31+ int end = i+l-1 ;
32+
33+ if (s[i] == s[end]){
34+ dp[i][end] = dp[i+1 ][end-1 ];
35+ if (dp[i][end] == true ){
36+ ans = l;
37+ st = i;
38+ }
39+ }
40+ else {
41+ dp[i][end] = false ;
42+ }
43+ }
44+ }
45+ // printing the substring
46+ return s.substr (st, ans);
47+ }
48+ };
149
You can’t perform that action at this time.
0 commit comments