Medium
You are given two strings skill and station of lengths n and m, respectively.
skill[i] represents the skill of worker i, and station[j] represents the skill supported by station j.
You must assign every worker to a distinct station. Let ji be the index of the station assigned to worker i. A valid assignment must satisfy:
station[ji] == skill[i] for every 0 <= i < n.j0 < j1 < ... < jn - 1.The gap of an assignment is the maximum difference between the station indices assigned to two consecutive workers. In other words, it is max(ji - ji - 1) over all 1 <= i < n.
If there is only one worker, the gap is 0.
Return the maximum possible gap among all valid assignments. It is guaranteed that at least one valid assignment exists.
Example 1:
Input: skill = “aa”, station = “aaaa”
Output: 3
Explanation:
'a' stations.[0, 3] gives a gap of 3.Example 2:
Input: skill = “xyz”, station = “xyzz”
Output: 2
Explanation:
j = 0, and worker 1 to station j = 1.j = 3.[0, 1, 3] with gaps [1, 2], so the gap is 2.Example 3:
Input: skill = “cbc”, station = “cbcdbc”
Output: 4
Explanation:
j = 0, and worker 1 to station j = 1.j = 5.[0, 1, 5] with gaps [1, 4], so the gap is 4.Constraints:
skill.length == nstation.length == m1 <= n <= m <= 105skill and station consist of lowercase English letters.public class Solution {
public int maximumGap(String skill, String station) {
if (skill.length() == 1) {
return 0;
}
return maximumGap(skill.toCharArray(), station.toCharArray());
}
private static int maximumGap(char[] skill, char[] station) {
int n = skill.length;
int[] last = new int[n];
int pos = station.length - 1;
for (int i = n - 1; i >= 0; --i) {
while (station[pos] != skill[i]) {
--pos;
}
last[i] = (pos--);
}
int result = 0;
pos = 0;
for (int i = 0, limit = n - 1; i < limit; ++i) {
while (station[pos] != skill[i]) {
++pos;
}
result = Math.max(result, last[i + 1] - pos);
++pos;
}
return result;
}
}