20251112 baekjoon
This commit is contained in:
parent
7e261a42d8
commit
cc54ff86f3
51
code_study/Baekjoon/swift/9252.swift
Normal file
51
code_study/Baekjoon/swift/9252.swift
Normal file
@ -0,0 +1,51 @@
|
||||
if let in1 = readLine(), let in2 = readLine()
|
||||
{
|
||||
let s1: [Character] = Array(in1)
|
||||
let s2: [Character] = Array(in2)
|
||||
let (l1, l2) = (s1.count, s2.count)
|
||||
var dp: [[Int]] = Array(repeating: Array(repeating: 0, count: l2+1), count: l1+1)
|
||||
|
||||
for i in 1...l1 {
|
||||
|
||||
let c1 = s1[i-1]
|
||||
|
||||
for j in 1...l2 {
|
||||
|
||||
let c2 = s2[j-1]
|
||||
|
||||
if c1 == c2 {
|
||||
dp[i][j] = dp[i-1][j-1] + 1
|
||||
}
|
||||
else {
|
||||
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
print(dp[l1][l2])
|
||||
|
||||
if dp[l1][l2] != 0 {
|
||||
var result: String = ""
|
||||
var (p1, p2) = (l1, l2)
|
||||
|
||||
while !(p1 == 0 || p2 == 0) {
|
||||
let (c1, c2) = (s1[p1-1], s2[p2-1])
|
||||
|
||||
if c1 == c2 {
|
||||
result.append(c1)
|
||||
(p1, p2) = (p1-1, p2-1)
|
||||
}
|
||||
else {
|
||||
if dp[p1-1][p2] > dp[p1][p2-1] {
|
||||
p1 -= 1
|
||||
}
|
||||
else {
|
||||
p2 -= 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
print(String(Array(result).reversed()))
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user