算法设计与应用基础:第十六周

来源:互联网 发布:淘宝客服售后用语大全 编辑:程序博客网 时间:2024/06/06 16:25

516. Longest Palindromic Subsequence

DescriptionHintsSubmissionsSolutions
  • Total Accepted: 10598
  • Total Submissions: 24947
  • Difficulty: Medium
  • Contributors:Stomach_ache

Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.

Example 1:
Input:

"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".

Example 2:
Input:

"cbbd"
Output:
2

One possible longest palindromic subsequence is "bb".


题解:运用递归的思想,当一个子序列长度为1时,最长回文长度为1,当长度为2时,若两位相等,则最长长度为2,否则为1。

当向一个已知最长回文长度的子序列的两边各加一位时,若两位相等,则最长长度是“只加左边”、“只加右边”、“原长度+2”三种情况的最大值。

若两位不相等,则是“只加左边”、“只加右边”、“原长度”三种情况的最大值。代码如下:



原创粉丝点击