leetcode516 最长回文子序列
生活随笔
收集整理的這篇文章主要介紹了
leetcode516 最长回文子序列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個字符串s,找到其中最長的回文子序列??梢约僭Os的最大長度為1000。
示例 1:
輸入:
"bbbab"
輸出:
4
一個可能的最長回文子序列為 "bbbb"。
示例 2:
輸入:
"cbbd"
輸出:
2
一個可能的最長回文子序列為 "bb"。
思路:
class Solution {public int longestPalindromeSubseq(String s) {int n = s.length();int[][] f = new int[n][n];for (int i = n - 1; i >= 0; i--) {f[i][i] = 1;for (int j = i + 1; j < n; j++) {if (s.charAt(i) == s.charAt(j)) {f[i][j] = f[i + 1][j - 1] + 2;} else {f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]);}}}return f[0][n - 1];} }總結
以上是生活随笔為你收集整理的leetcode516 最长回文子序列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS演示图论汇总
- 下一篇: leetcode169. 多数元素