516. Longest Palindromic Subsequence

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".

Subscribe to see which companies asked this question.

public class Solution {
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
		int[][] data = new int[n + 1][n + 1];
		for (int i = 0; i < n; ++i) {
			data[0][i] = 0;
			data[i][0] = 0;
		}
		for (int i = 1; i <= n; ++i) {
			for (int j = 1; j <= n; ++j) {
				if (s.charAt(i - 1) == s.charAt(n - j))
					data[i][j] = data[i - 1][j - 1] + 1;
				else
					data[i][j] = Math.max(data[i][j - 1], data[i - 1][j]);
			}
		}
		return data[n][n];
    }
}


你可能感兴趣的:(Leetcode)