Input: initial ="abcde", target ="cdef"Output: 3Explanation:
Remove `'a'` and `'b'` from the beginning of `initial`, then add `'f'` to the
end.
Example 2:
1
2
3
4
5
6
7
8
9
10
11
Input: initial ="axxy", target ="yabx"Output: 6Explanation:
Operation | Resulting String
---|---Add `'y'` to the beginning |`"yaxxy"`Remove from end |`"yaxx"`Remove from end |`"yax"`Remove from end |`"ya"`Add `'b'` to the end |`"yab"`Add `'x'` to the end |`"yabx"`
Example 3:
1
2
3
4
Input: initial ="xyz", target ="xyz"Output: 0Explanation:
No operations are needed as the strings are already equal.
Constraints:
1 <= initial.length, target.length <= 1000
initial and target consist only of lowercase English letters.
The only way to transform initial into target using allowed operations is to match a substring of target somewhere in initial and add/remove characters at the ends. The minimum number of operations is the sum of the characters to remove from the ends of initial and the characters to add to match target.
classSolution {
public:int minOperations(string initial, string target) {
int n = initial.size(), m = target.size(), ans = n + m;
for (int i =0; i < n; ++i) {
for (int j =0; j < m; ++j) {
int len =0;
while (i + len < n && j + len < m && initial[i + len] == target[j + len]) ++len;
if (len >0) {
int ops = i + (n - (i + len)) + j + (m - (j + len));
ans = min(ans, ops);
}
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintminOperations(String initial, String target) {
int n = initial.length(), m = target.length(), ans = n + m;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int len = 0;
while (i + len < n && j + len < m && initial.charAt(i + len) == target.charAt(j + len)) ++len;
if (len > 0) {
int ops = i + (n - (i + len)) + j + (m - (j + len));
ans = Math.min(ans, ops);
}
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defminOperations(self, initial: str, target: str) -> int:
n, m = len(initial), len(target)
ans = n + m
for i in range(n):
for j in range(m):
l =0while i + l < n and j + l < m and initial[i + l] == target[j + l]:
l +=1if l >0:
ops = i + (n - (i + l)) + j + (m - (j + l))
ans = min(ans, ops)
return ans
impl Solution {
pubfnmin_operations(initial: String, target: String) -> i32 {
let n = initial.len();
let m = target.len();
let initial = initial.as_bytes();
let target = target.as_bytes();
letmut ans = (n + m) asi32;
for i in0..n {
for j in0..m {
letmut l =0;
while i + l < n && j + l < m && initial[i + l] == target[j + l] {
l +=1;
}
if l >0 {
let ops = i + (n - (i + l)) + j + (m - (j + l));
ans = ans.min(ops asi32);
}
}
}
ans
}
}