|
| 1 | + |
| 2 | +import java.util.ArrayList; |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +class Solution { |
| 8 | + private Map<String, Integer> memo = new HashMap<>(); |
| 9 | + |
| 10 | + public int longestCommonSubsequence(String t1, String t2) { |
| 11 | + return lcs(0, 0, t1, t2); |
| 12 | + } |
| 13 | + |
| 14 | + private int lcs(int i, int j, String t1, String t2) { |
| 15 | + if (i == t1.length() || j == t2.length()) { |
| 16 | + return 0; |
| 17 | + } |
| 18 | + |
| 19 | + String key = i + "," + j; |
| 20 | + if (memo.containsKey(key)) { |
| 21 | + return memo.get(key); |
| 22 | + } |
| 23 | + |
| 24 | + int res; |
| 25 | + if (t1.charAt(i) == t2.charAt(j)) { |
| 26 | + res = 1 + lcs(i + 1, j + 1, t1, t2); |
| 27 | + } else { |
| 28 | + res = Math.max(lcs(i + 1, j, t1, t2), lcs(i, j + 1, t1, t2)); |
| 29 | + } |
| 30 | + |
| 31 | + memo.put(key, res); |
| 32 | + return res; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +class WrongSolution { |
| 37 | + public int longestCommonSubsequence(String t1, String t2) { |
| 38 | + Map<Integer, List<Integer>> sMap = new HashMap<>(); |
| 39 | + int cnt = 0; |
| 40 | + |
| 41 | + // t1μ μ°μμΌλ‘ λ±μ₯νλ λ¬Έμμ΄μ νλλ‘λ§ λ°κΎΈκΈ° (e.g. abbbvvvvssssmmmddd -> abvsmd) |
| 42 | + StringBuilder sb = new StringBuilder(); |
| 43 | + char start = t1.charAt(0); |
| 44 | + sb.append(start); |
| 45 | + for (int i = 1; i < t1.length(); i++) { |
| 46 | + if (start != t1.charAt(i)) { |
| 47 | + sb.append(t1.charAt(i)); |
| 48 | + start = t1.charAt(i); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + t1 = sb.toString(); |
| 53 | + |
| 54 | + for (int i = 0; i < t1.length(); i++) { |
| 55 | + sMap.computeIfAbsent(t1.charAt(i) - 97, k -> new ArrayList<>()).add(i); |
| 56 | + } |
| 57 | + |
| 58 | + StringBuilder filtered = new StringBuilder(); |
| 59 | + for (int i = 0; i < t2.length(); i++) { |
| 60 | + int alpIdx = t2.charAt(i) - 97; |
| 61 | + if (sMap.containsKey(alpIdx)) { |
| 62 | + filtered.append(t2.charAt(i)); |
| 63 | + } |
| 64 | + } |
| 65 | + t2 = filtered.toString(); |
| 66 | + |
| 67 | + int prevT1Idx = -1; |
| 68 | + for (int i = 0; i < t2.length(); i++) { |
| 69 | + int alpIdx = t2.charAt(i) - 97; |
| 70 | + |
| 71 | + List<Integer> idxList = sMap.get(alpIdx); |
| 72 | + if (idxList == null) |
| 73 | + continue; |
| 74 | + |
| 75 | + for (int idx : idxList) { |
| 76 | + if (idx > prevT1Idx) { |
| 77 | + cnt++; |
| 78 | + prevT1Idx = idx; |
| 79 | + break; |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + return cnt; |
| 85 | + } |
| 86 | +} |
0 commit comments