---
# System prepended metadata

title: 2023. Number of Pairs of Strings With Concatenation Equal to Target
tags: [Leetcode, String, Medium]

---

# 2023. Number of Pairs of Strings With Concatenation Equal to Target
###### tags: `Leetcode` `Medium` `String`
Link: https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/
## 思路 $O(N)$ $O(N)$
如果把if都合并起来的话，就会有问题。例如如果target是"7777", nums里面有一个"77", 那么它会先被加到prefix_map里面，然后在第二个if的时候，就会因为存在len=2的prefix，cnt+1（但实际上不应该+1，因为这样相当于自己跟自己combine）
## Code
```java=
class Solution {
    public int numOfPairs(String[] nums, String target) {
        Map<Integer, Integer> prefix_map = new HashMap<Integer, Integer>();
        Map<Integer, Integer> suffix_map = new HashMap<Integer, Integer>();
        int cnt = 0;
        int targetLen = target.length();
        for(String num:nums){
            int numLen = num.length();
            if(target.startsWith(num)){
                cnt += suffix_map.getOrDefault(targetLen-numLen,0);
            }
            if(target.endsWith(num)){
                cnt += prefix_map.getOrDefault(targetLen-numLen,0);
            }
            if(target.startsWith(num)){
                prefix_map.put(numLen, prefix_map.getOrDefault(numLen,0)+1);
            }
            if(target.endsWith(num)){
                suffix_map.put(numLen, suffix_map.getOrDefault(numLen,0)+1);
            }
            
        }
        return cnt;
    }
}
```