Number of Pairs of Strings With Concatenation Equal to Target
给一个字符串组和一个target字符串, 问有多少个pair,组成target.
这题字符串组有重复, 所以先要counting一下, 然后切割target, 因为切割后的两个部分有可能相同, 相同的时候是C(n,n-1)个, 不同的时候是n* n-1个.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Solution { public int numOfPairs(String[] nums, String target) { Map<String, Integer> count = new HashMap<>(); for(String s : nums){ count.put(s, count.getOrDefault(s, 0) + 1); } int res = 0; for(int i = 1; i < target.length(); i++) { String a = target.substring(0, i); String b = target.substring(i, target.length()); if(count.containsKey(a) && count.containsKey(b)){ if(a.equals(b)){ int n = count.get(a); res += n * (n - 1); }else { res += count.get(a) * count.get(b); } } } return res; } } |