51Nod 1092 回文字串(區間dp)

2021-08-30 17:39:19 字數 729 閱讀 5827

回文串是指aba、abba、cccbccc、aaaa這種左右對稱的字串。每個字串都可以通過向中間新增一些字元,使之變為回文字串。

例如:abbc 新增2個字元可以變為 acbbca,也可以新增3個變為 abbcbba。方案1只需要新增2個字元,是所有方案中新增字元數量最少的。

收起

輸入乙個字串str,str的長度 <= 1000。
輸出最少新增多少個字元可以使之變為回文字串。
abbc
2
dp[i][j]二維陣列表示的是從位置i到j所需要新增的最少字元。

遞推公式:

if(s[i]==s[j])

dp[i][j]=dp[i+1][j-1]

else 

dp[i][j]=min(dp[i+1][j],dp[i][j-1])+1

**如下:

#include #include #include #include using namespace std;

const int maxn=1005;

char s[maxn];

int dp[maxn][maxn];

int main()

for (int i=0;ielse

}for (int i=2;ielse}}

printf("%d\n",dp[0][len-1]);

return 0;

}

51nod 1092 回文字串

1092 回文字串 基準時間限制 1 秒 空間限制 131072 kb 分值 10 難度 2級演算法題 收藏 關注 回文串是指aba abba cccbccc aaaa這種左右對稱的字串。每個字串都可以通過向中間新增一些字元,使之變為回文字串。例如 abbc 新增2個字元可以變為 acbbca,也可...

51nod 1092 回文字串

題解 本題要求的是求最小新增的數,那麼可以進行反向的思考,直接算最大的公共長度,然後用總長度 最的公共長度之後,就是答案了。include include include include include using namespace std const int maxn 1000 10 defin...

51nod 1092 回文字串

1092 回文字串 難度 2級演算法題 回文串是指aba abba cccbccc aaaa這種左右對稱的字串。每個字串都可以通過向中間新增一些字元,使之變為回文字串。例如 abbc 新增2個字元可以變為 acbbca,也可以新增3個變為 abbcbba。方案1只需要新增2個字元,是所有方案中新增字...