返回输入二维字符矩阵中班3*3子矩阵中含有xiaomi字符的个数,保证矩阵大小>=3;
输入:
4 4
xiaq
oime
xaic
cadf
输出
2
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
sc.nextLine();
char[][] chars = new char[4][4];
for (int i = 0; i < n; i++) {
chars[i] = sc.nextLine().toCharArray();
}
System.out.println(solution(chars));
}
//3*3的matrix,xiaomi
private static int solution(char[][] strings) {
HashMap<Character, Integer> need = new HashMap<>();
HashMap<Character, Integer> window = new HashMap<>();
String p = "xiaomi";
for (char c : p.toCharArray()) {
need.put(c, need.getOrDefault(c, 0) + 1);
}
// System.out.println(p);
int left = 0, right = 0;//[)
int valid = 0;
int ans = 0;
int k = 3;
//00-33
for (int i = 0; i+3 <= strings.length; i++) {
window.clear();
valid = cmp(i, strings, window, need, k);
right = 3;left = 0;
while (right<strings[0].length){
// System.out.println("valid=" + valid);
if (valid == need.size()) ans++;
//判断是否满足 然后移动
for (int j = i; j < i+3; j++) {
char c = strings[j][right];
if (need.containsKey(c)){
window.put(c,window.getOrDefault(c,0)+1);
if (window.get(c).equals(need.get(c))) valid++;
}
//移除
char d = strings[j][left];
if (need.containsKey(d)){
if (window.get(d).equals(need.get(d))) valid--;
window.put(d,window.get(d)-1);
}
}
right++;left++;
}
}
return ans;
}
/**
*
* @param strings 原字符
* @param window 窗口值
* @param need 需要匹配
* @param k 窗口长度
*/
public static int cmp(int startX,char[][] strings,HashMap<Character,Integer> window,HashMap<Character,Integer> need,int k){
//valid 满足字符数
int valid = 0;
for (int i = startX; i < startX+k; i++) {
for (int j = 0; j < k; j++) {
char c = strings[i][j];
if (need.containsKey(c)){
window.put(c, window.getOrDefault(c, 0) + 1);
if (window.get(c).equals(need.get(c))) valid++;
}
}
}
return valid;
}
private static void func(LinkedList<Integer> ans) {
System.out.println(ans);
}
}