关键字:字符串计数、字符串分割枚举
package dailyexecise;
import java.util.HashMap;
import java.util.Map;
public class numOfPairs2023 {
public static void main(String[] args) {
String test = "12345";
System.out.println(test.substring(0, 2));
System.out.println(test.substring(3));
}
public int numOfPairs(String[] nums, String target) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
String resStr = nums[i] + nums[j];
if (i != j && target.equals(resStr)) {
count++;
}
}
}
return count;
}
public int numOfPairs2(String[] nums, String target) {
int count = 0;
for (int i = 0; i < nums.length - 1; i++) {
// 题目要求需满足 i != j
for (int j = i+1; j < nums.length; j++) {
String resStr = nums[i] + nums[j];
if (target.equals(nums[i] + nums[j])) {
count++;
}
if (target.equals(nums[j] + nums[i])) {
count++;
}
}
}
return count;
}
public int numOfPairs3(String[] nums, String target) {
// 字符数组计数
Map<String, Integer> countMap = new HashMap<>();
for (String num : nums) {
// key ,insert-value,merge-function
countMap.merge(num, 1, (old, newValue) -> old + 1);
}
int ans = 0;
// 分解字符串,获取字符串枚举方案
for (int i = 1; i < target.length(); i++) {
// substring左闭右开
String left = target.substring(0, i);
String right = target.substring(i);
if (left.equals(right)) {
// 想不清楚就模拟咯
ans += countMap.getOrDefault(left, 0) * (countMap.getOrDefault(right, 0) - 1);
} else {
ans += countMap.getOrDefault(right, 0) * countMap.getOrDefault(left, 0);
}
}
return ans;
}
}