|
| 1 | +# Diff Between Two Strings |
| 2 | + |
| 3 | +Given two strings of uppercase letters source and target, list (in string form) a sequence of edits to convert from source to target that uses the least edits possible. |
| 4 | + |
| 5 | +For example, with strings source = "ABCDEFG", and target = "ABDFFGH" we might return: ["A", "B", "-C", "D", "-E", "F", "+F", "G", "+H" |
| 6 | + |
| 7 | +More formally, for each character C in source, we will either write the token C, which does not count as an edit; or write the token -C, which counts as an edit. |
| 8 | + |
| 9 | +Additionally, between any token that we write, we may write +D where D is any letter, which counts as an edit. |
| 10 | + |
| 11 | +At the end, when reading the tokens from left to right, and not including tokens prefixed with a minus-sign, the letters should spell out target (when ignoring plus-signs.) |
| 12 | + |
| 13 | +In the example, the answer of A B -C D -E F +F G +H has total number of edits 4 (the minimum possible), and ignoring subtraction-tokens, spells out A, B, D, F, +F, G, +H which represents the string target. |
| 14 | + |
| 15 | +If there are multiple answers, use the answer that favors removing from the source first. |
| 16 | + |
| 17 | +Constraints: |
| 18 | + |
| 19 | +[time limit] 5000ms |
| 20 | + |
| 21 | +[input] string source |
| 22 | +2 ≤ source.length ≤ 12 |
| 23 | + |
| 24 | +[input] string target |
| 25 | +2 ≤ target.length ≤ 12 |
| 26 | + |
| 27 | +[output] array.string |
| 28 | + |
| 29 | +# Solution |
| 30 | + |
| 31 | +The trickiest part of all this is to build the intuition for how to handle the fork. |
| 32 | +You should notice that there are only two possible ways when a char from target and source do not match. |
| 33 | +Whether to delete S or add T. |
| 34 | +We would have to traverse the entire solution space because we don't know if we can build a smaller list. |
| 35 | +After that, its a simpler recursive call and returning the min list. |
| 36 | + |
| 37 | +``` |
| 38 | +def diffBetweenTwoStrings(source, target): |
| 39 | + def diff_helper(s, t): |
| 40 | + if len(t) == 0 and len(s) > 0: |
| 41 | + return ['-' + ch for ch in s] |
| 42 | + elif len(t) > 0 and len(s) == 0: |
| 43 | + return ['+' + ch for ch in t] |
| 44 | + elif len(t) == 0 and len(s) == 0: |
| 45 | + return [] |
| 46 | + if s[0] == t[0]: |
| 47 | + return [s[0]] + diff_helper(s[1:], t[1:]) |
| 48 | + # s[0] != t[0] |
| 49 | + result1 = diff_helper(s[1:], t) # skip s, delete s |
| 50 | + result2 = diff_helper(s, t[1:]) # skip t, add t |
| 51 | + if len(result1) <= len(result2): |
| 52 | + return ['-' + s[0]] + result1 |
| 53 | + else: |
| 54 | + return ['+' + t[0]] + result2 |
| 55 | + |
| 56 | + return diff_helper(source, target) |
| 57 | +``` |
0 commit comments