题目地址:
https://www.lintcode.com/problem/841/
给定两个等长的字符串数组 A A A和 B B B,题目保证 l A [ i ] = l B [ i ] l_{A[i]}=l_{B[i]} lA[i]=lB[i],并且 ∀ i ≠ j , A [ i ] ≠ A [ j ] \forall i\ne j, A[i]\ne A[j] ∀i=j,A[i]=A[j]。再给定一个长 n n n的字符串 s s s,要求对 s s s做如下处理:从左到右遍历 s s s,当发现从某个位置开始的一段恰好等于 A A A中某个字符串 A [ i ] A[i] A[i]的时候,一定要将其换为 B [ i ] B[i] B[i];如果发现它等于 A A A中多个字符串,则取长度最长的那个。已经换过的位置以后不许再换。求最终 s s s变成了什么。
可以先将 A A A中的字符串按长度从大到小排序(真实代码里可以只对下标排序)。接着算出 A A A中所有字符串的哈希值,然后算出 s s s的前缀哈希数组,接下来就可以开始遍历 s s s了。对每个位置,直接按长度从长到短枚举 A A A里的每个字符串是否能发生匹配,如果发生,就直接替换,并且将指针挪到替换完之后的位置。代码如下:
import java.util.ArrayList;
import java.util.List;
public class Solution {
/**
* @param a: The A array
* @param b: The B array
* @param s: The S string
* @return: The answer
*/
public String stringReplace(String[] a, String[] b, String s) {
// Write your code here
char[] chs = s.toCharArray();
long P = 131;
List<Integer> id = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
id.add(i);
}
// 将下标按字符串长度从大到小排序
id.sort((x, y) -> -Integer.compare(a[x].length(), a[y].length()));
// 把a中每个字符串的哈希值存入一个列表中,按长度从大到小存
List<Long> hashList = new ArrayList<>();
for (int idx : id) {
String t = a[idx];
long hashT = 0;
for (int j = 0; j < t.length(); j++) {
hashT = hashT * P + t.charAt(j);
}
hashList.add(hashT);
}
int n = chs.length;
// 求一下s的前缀哈希数组
long[] hash = new long[n + 1], pow = new long[n + 1];
pow[0] = 1;
for (int i = 0; i < n; i++) {
hash[i + 1] = hash[i] * P + chs[i];
pow[i + 1] = pow[i] * P;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < id.size(); j++) {
String old = a[id.get(j)], repl = b[id.get(j)];
long hashOld = hashList.get(j);
// 如果发生了匹配,就开始替换
if (i + old.length() - 1 < n && getHash(hash, i, i + old.length() - 1, pow) == hashOld) {
for (int k = 0; k < old.length(); k++) {
chs[i + k] = repl.charAt(k);
}
// 替换完成之后将i向后挪
i += old.length() - 1;
break;
}
}
}
return new String(chs);
}
long getHash(long[] hash, int l, int r, long[] pow) {
return hash[r + 1] - hash[l] * pow[r - l + 1];
}
}
时间复杂度 O ( l A n ) O(l_An) O(lAn),空间 O ( l A + n ) O(l_A+n) O(lA+n)。