λ¬Έμ
νμ΄
νλ£¨μ’ μΌ μ΄ λ¬Έμ λ§ λΆλ€κ³ μμλ κ² κ°λ€. μ²μ μλνλ λ°©λ²μ μΌμ°¨μ λ°°μ΄μ ν΅ν΄ λ©λͺ¨μ΄μ μ΄μ μ μννκ³ μ νλ€. νμ§λ§ μΌμ°¨μ λ°°μ΄μ μ¬μ©νλ κ²½μ°μλ κ°μ λ¬Έμκ° μ¬λ¬λ² λ±μ₯ν κ²½μ°μ λν΄μ μλͺ»λ μ΅λκ°μ μ»λ κ²½μ°κ° λ°μνλ€.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int[][] cache;
public static void main(String[] args) throws IOException {
String s1 = br.readLine();
String s2 = br.readLine();
boolean isS1 = (s1.length() < s2.length()) ? true : false;
int len = (s1.length() < s2.length()) ? s1.length() : s2.length();
cache = new int[len + 1][2];
if (isS1) {
System.out.println(getLCS(s1, s2, len));
} else {
System.out.println(getLCS(s2, s1, len));
}
}
static int getLCS(String smaller, String longer, int len) {
cache[len][0] = 0;
cache[len][1] = len-1;
for (int i = len - 1; i >= 0; i--) {
char target = smaller.charAt(i);
int maxCnt = 0;
int maxIdx = -1;
for (int j = i + 1; j <= len; j++) {
int idx = longer.substring(0, cache[j][1] + 1).lastIndexOf(target);
if (idx < 0)
continue;
if (maxCnt < cache[j][0] + 1) {
maxCnt = cache[j][0] + 1;
maxIdx = idx;
} else if (maxCnt == cache[j][0] + 1) {
maxIdx = (maxIdx < idx) ? idx : maxIdx;
}
}
cache[i][0] = maxCnt;
cache[i][1] = maxIdx;
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {
if (max < cache[i][0])
max = cache[i][0];
}
return max;
}
}
κ·Έλμ λͺ¨λ κ²½μ°μ μλ₯Ό μ μ μκΈ° μν΄μ μ΄μ°¨μ λ°°μ΄μ ν΅ν΄ λ©λͺ¨μ΄μ μ΄μ μ μκ°νλ€. μ΄μ°¨μμΌλ‘ μννλ κ²½μ°, κ° μ리κΉμ§μ μ΅λ LCSλ₯Ό μ μ§νλ λ°©μμΌλ‘ λ©λͺ¨μ΄μ μ΄μ μ μνν΄μΌνλ€. μ’ λ μμΈν 보면 λ§μ½ ν΄λΉ μ리μ κ°μ λ¬ΈμμΈ κ²½μ°μλ μ΄μ μ κ·Έ μ리κΉμ§ μ μ μ΅λκ° + 1μ΄ λκ³ λ§μ½ κ°μ§ μλ€λ©΄ μ΄μ λ¬Έμμ μ΅λκ°(μ΄μ ν)κ³Ό μ΄λ² λ¬Έμλ₯Ό λΉκ΅νλ©΄μ μκΈ΄ μ΅λκ°(μ΄μ μ΄) μ€μμ μ΅λκ°μ΄ λλ€.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution9251 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int[][] cache;
public static void main(String[] args) throws IOException {
String row = br.readLine();
String col = br.readLine();
cache = new int [row.length() + 1][col.length() + 1];
for (int i = 1; i < row.length() + 1; i++) {
for (int j = 1; j < col.length() + 1; j++) {
if (row.charAt(i - 1) == col.charAt(j - 1)) {
cache[i][j] = cache[i-1][j-1] + 1;
} else {
cache[i][j] = Integer.max(cache[i-1][j], cache[i][j-1]);
}
}
}
System.out.println(cache[row.length()][col.length()]);
}
}
'π Algorithm > π» λ¬Έμ νμ΄' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[λ°±μ€] 3109. λΉ΅μ§ (0) | 2021.02.19 |
---|---|
[λ°±μ€] 15686. μΉν¨ λ°°λ¬ (0) | 2021.02.19 |
[λ°±μ€] 11053. κ°μ₯ κΈ΄ μ¦κ°νλ λΆλΆ μμ΄ (0) | 2021.02.10 |
[λ°±μ€] 9663. N-Queens (0) | 2021.02.05 |
[λ°±μ€] 2493. ν (0) | 2021.02.04 |
λκΈ