dp回文

时间:2022-02-09 21:36:19

。dp回文子串 通常在dp数组中存放的是 从i到j是否是回文子串

1.动态规划

2.中心扩展法

 #include<iostream>
 #include<algorithm>
 #include<string>
 using namespace std;
 ][] = {  };
 int main(void)
 {
     string s1;
     while (cin >> s1)
     {
         int length = s1.length();
         int i;
         ; i <= length - ; ++i)
             dp[i][i] = ;
         int j;
         ; i >=; --i)
         {
             ; j <=length-; ++j)
             {
                 if (s1[i] == s1[j])
                 {
                     dp[i][j] = dp[i + ][j - ] + ;
                 }
                 else
                 {
                     dp[i][j] = max(dp[i + ][j], dp[i][j - ]);
                 }
             }
         }
         cout << ][length - ] << endl;
     }
     ;
 }
 #include<iostream>
 #include<algorithm>
 #include<string>
 using namespace std;
 ][] = {  };
 int main(void)
 {
     string s1;
     while (cin >> s1)
     {
         int length = s1.length();
         int i;
         ; i <= length - ; ++i)
             dp[i][i] = ;
         int j;
         ; i >= ; --i)
         {
             ; j <= length - ; ++j)
             {
                 if (s1[i] != s1[j])
                 {
                     dp[i][j] = dp[i + ][j] + dp[i][j - ] - dp[i + ][j - ];
                 }
                 else
                 {
                     dp[i][j] = dp[i + ][j] + dp[i][j - ] - dp[i + ][j - ] + dp[i + ][j - ] + ;
                 }
             }
         }
         cout << ][length - ] << endl;
     }
     ;
 }
 #include<iostream>
 #include<algorithm>
 #include<string>
 using namespace std;
 ];           //长度
 bool ispalindrome(string s,int start,int end)
 {
     while (start <= end)
     {
         if (s[start] != s[end])
         {
             return false;
         }
         ++start;
         --end;
     }
     return true;
 }
 int main(void)
 {
     string s;
     while (cin >> s)
     {
         int length = s.length();
         int i;
         ; i <= length; ++i)
         {
             dp[i] = i - ;
             , i-) == true)
             {
                 dp[i] = ;
             }
         }
         int j;
         ; i <= length-; ++i)
         {
             ; j <= i; ++j)
             {
                 if (ispalindrome(s, j, i) == true)
                 {
                     dp[i + ] = min(dp[i + ], dp[j] + );
                 }
             }
         }
         cout << "需要分割的次数为" << dp[length] << "次"<<endl;
     }
     ;
 }