Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c4f6c29

Browse files
516. Longest Palindromic Subsequence
1 parent 9869afc commit c4f6c29

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import 'dart:math';
2+
3+
/// The time complexity of the `longestPalindromeSubseq` function is `O(n^2)`,
4+
/// where `n` is the length of the input string `s`. This is because the function
5+
/// uses a dynamic programming approach to compute the length of the longest
6+
/// palindromic subsequence of `s`, which involves filling in an `n * n` table of values.
7+
/// The space complexity of the function is also `O(n^2)`, since it uses a 2D list `dp`
8+
/// of size `n * n` to store the intermediate results of the dynamic programming algorithm.
9+
10+
class Solution {
11+
int longestPalindromeSubseq(String s) {
12+
int n = s.length;
13+
List<List<int>> dp = List.generate(n, (_) => List.filled(n, 0));
14+
15+
for (int i = n - 1; i >= 0; i--) {
16+
dp[i][i] = 1;
17+
for (int j = i + 1; j < n; j++) {
18+
if (s[i] == s[j]) {
19+
dp[i][j] = dp[i + 1][j - 1] + 2;
20+
} else {
21+
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
22+
}
23+
}
24+
}
25+
26+
return dp[0][n - 1];
27+
}
28+
}
29+
30+
void main(List<String> args) {
31+
print(Solution().longestPalindromeSubseq('bbbab'));
32+
}
33+
34+
/// NB: The time complexity of the `longestPalindromeSubseq` function
35+
/// is optimal at `O(n^2)`, where `n` is the length of the input string `s`.
36+
/// This is because any algorithm that solves the longest palindromic
37+
/// subsequence problem must examine every possible substring of `s`,
38+
/// which takes `O(n^2)` time.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
516. Longest Palindromic Subsequence
2+
https://leetcode.com/problems/longest-palindromic-subsequence/
3+
4+
Given a string s, find the longest palindromic subsequence's length in s.
5+
6+
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
7+
8+
9+
Example 1:
10+
11+
Input: s = "bbbab"
12+
Output: 4
13+
Explanation: One possible longest palindromic subsequence is "bbbb".
14+
15+
Example 2:
16+
17+
Input: s = "cbbd"
18+
Output: 2
19+
Explanation: One possible longest palindromic subsequence is "bb".
20+
21+
22+
Constraints:
23+
24+
1 <= s.length <= 1000
25+
s consists only of lowercase English letters.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /