Skip to content

Commit d847521

Browse files
committed
Create 0516-longest-palindromic-subsequence.swift
1 parent 32bb838 commit d847521

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/longest-palindromic-subsequence/
3+
*/
4+
5+
class Solution {
6+
func longestPalindromeSubseq(_ s: String) -> Int {
7+
let s = Array(s)
8+
let n = s.count
9+
var dp = Array(repeating: 0, count: n)
10+
var dpPrev = Array(repeating: 0, count: n)
11+
12+
for i in stride(from: s.count - 1, to: -1, by: -1) {
13+
dp[i] = 1
14+
for j in i + 1..<n {
15+
if s[i] == s[j] {
16+
dp[j] = dpPrev[j - 1] + 2
17+
} else {
18+
dp[j] = max(dpPrev[j], dp[j - 1])
19+
}
20+
}
21+
dpPrev = dp
22+
}
23+
24+
return dp[n - 1]
25+
}
26+
}

0 commit comments

Comments
 (0)