小美的字符串匹配度(美团2024届秋招笔试第一场编程真题)

题面

核心思想

首先对于本来就匹配的肯定不能动

第一次遍历 对于匹配的res++ 对于不匹配的

用HashMap<Character, List> mp

存放当s[i]!=t[i]时 字符t[i]的下标i,表示t[i]的这个字符出现在t的位置

然后我们在做一次遍历

当s[i]!=t[i]时 且 t 中存在字符s[i](用我们第一次遍历的 mp 判断) 则尝试交换 那么首先交换过来的肯定能和s[i]匹配 还要判断交换过去的会不会匹配。

代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        final long MOD = (long) (1e9 + 7);
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        String s = scanner.nextLine();
        String t = scanner.nextLine();
        // 存放不匹配字符t的下标
        HashMap<Character, List<Integer>> mp = new HashMap<>();
        int res = 0;
        for(int i = 0; i < n; i++){
            if(s.charAt(i) == t.charAt(i))
                res++;
            else{
                //存放下标
                List<Integer> idx = mp.getOrDefault(t.charAt(i), new ArrayList<>());
                idx.add(i);
                mp.put(t.charAt(i), idx);
            }
        }
        //暂存res
        int resTmp = res;
        for(int i = 0; i < n; i++){
            // 不匹配 且 t中存在字符s[i]
            if(s.charAt(i) != t.charAt(i) && mp.containsKey(s.charAt(i))){
                List<Integer> idx = mp.get(s.charAt(i));
                for(int j = 0; j < idx.size(); j++){
                    // s  i   id
                    // t  i   id  s[i]一定是等于t[id]的 看i交换过去后能不能多一个匹配的
                    int cnt = 1;
                    int id = idx.get(j);
                    if(s.charAt(id) == t.charAt(i))
                        cnt++;
                    res = Math.max(res, resTmp + cnt);
                }
            }
        }
        System.out.println(res);
    }
}
posted @ 2024-04-02 14:36  Shie1d  阅读(178)  评论(0)    收藏  举报