-
Notifications
You must be signed in to change notification settings - Fork 1
/
NumberOfPairsOfStringsWithConcatenationEqualToTarget.java
63 lines (53 loc) · 1.77 KB
/
NumberOfPairsOfStringsWithConcatenationEqualToTarget.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/
public class NumberOfPairsOfStringsWithConcatenationEqualToTarget {
private final String[] nums;
private final String target;
public NumberOfPairsOfStringsWithConcatenationEqualToTarget(
String[] nums,
String target
) {
this.nums = nums;
this.target = target;
}
public int solution() {
Map<Integer, List<Pair>> pairs = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
String num = nums[i];
List<Pair> pair;
int length = num.length();
if (pairs.containsKey(length)) {
pair = pairs.get(length);
} else {
pair = new ArrayList<>();
}
pair.add(new Pair(i, num));
pairs.put(length, pair);
}
int result = 0;
for (int i = 0; i < nums.length; i++) {
String num = nums[i];
int candidateLength = target.length() - num.length();
if (pairs.containsKey(candidateLength)) {
for (Pair candidate : pairs.get(candidateLength)) {
if (candidate.index != i && (num + candidate.number).equals(target)) {
result++;
}
}
}
}
return result;
}
private static class Pair {
public final int index;
public final String number;
private Pair(int index, String number) {
this.index = index;
this.number = number;
}
}
}