【Leetcode】2023. Number of Pairs of Strings With Concatenation Equal to Target

题目地址:

https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/

给定一个只含数字的字符串数组 A A A,再给定一个字符串 s s s。问存在多少个 ( i , j ) , i ≠ j (i,j), i\ne j (i,j),i=j,使得 s = A [ i ] + A [ j ] s=A[i]+A[j] s=A[i]+A[j]

先将所有 A A A里的所有字符串进行哈希,然后求 s s s的前缀哈希数组,接着遍历 A A A,枚举当前字符串作为其中一个部分的情况,即枚举当前字符串作为前缀和作为后缀的情况,可以同时存一个HashMap存之前的字符串的哈希及其出现次数,这样可以迅速求出当前字符串作为前后缀能产生多少个pair。代码如下:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    
    
    public int numOfPairs(String[] nums, String s) {
    
    
        int n = s.length();
        long[] hashList = new long[nums.length], hashS = new long[n + 1], pow = new long[n + 1];
        long P = 131L;
        pow[0] = 1L;
        for (int i = 0; i < n; i++) {
    
    
            hashS[i + 1] = hashS[i] * P + s.charAt(i);
            pow[i + 1] = pow[i] * P;
        }
        
        for (int i = 0; i < nums.length; i++) {
    
    
            long hash = 0;
            String num = nums[i];
            for (int j = 0; j < num.length(); j++) {
    
    
                hash = hash * P + num.charAt(j);
            }
            
            hashList[i] = hash;
        }
        
        int res = 0;
        Map<Long, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
    
    
            int len = nums[i].length();
            // 如果当前字符串长度超过了s的长度,该字符串要略过
            if (len > n) {
    
    
                continue;
            }
            
            // 看nums[i]是否能作为s的前缀
            if (hashList[i] == getHash(hashS, 0, len - 1, pow)) {
    
    
                res += map.getOrDefault(getHash(hashS, len, n - 1, pow), 0);
            }
            // 看nums[i]是否能作为s的后缀
            if (hashList[i] == getHash(hashS, n - len, n - 1, pow)) {
    
    
                res += map.getOrDefault(getHash(hashS, 0, n - len - 1, pow), 0);
            }
            
            map.put(hashList[i], map.getOrDefault(hashList[i], 0) + 1);
        }
        
        return res;
    }
    
    long getHash(long[] hashS, int l, int r, long[] pow) {
    
    
        return hashS[r + 1] - hashS[l] * pow[r - l + 1];
    }
}

时间复杂度 O ( ∑ i l A [ i ] + l s ) O(\sum_i l_{A[i]}+l_s) O(ilA[i]+ls),空间 O ( l A + l s ) O(l_A+l_s) O(lA+ls)

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/120735792