0
点赞
收藏
分享

微信扫一扫

电脑版便签软件怎么设置在桌面上显示?

金穗_ec4b 2023-12-08 阅读 10

题目

思路

正则匹配

动态规划

同leetcode:10. 正则表达式匹配

题解

package hwod;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class StrMatch {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] strArr = sc.nextLine().split(" ");
        String p = sc.nextLine();
        List<Integer> res = strMatch2(strArr, p);
        if (res.size() == 0) {
            System.out.println(-1);
            return;
        }
        for (int i = 0; i < res.size(); i++) {
            if (i != 0) System.out.print(",");
            System.out.print(res.get(i));
        }

    }
    //方案一:正则匹配
    private static List<Integer> strMatch(String[] strArr, String p) {
        List<Integer> res = new ArrayList<>();
        p = "^" + p + "$";
        for (int i = 0; i < strArr.length; i++) {
            if (strArr[i].matches(p)) {
                res.add(i);
            }
        }
        return res;
    }

    //方案二:动态规划
    private static List<Integer> strMatch2(String[] strArr, String p) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < strArr.length; i++) {
            if (checked(strArr[i], p)) {
                res.add(i);
            }
        }
        return res;
    }

    private static boolean checked(String s, String p) {
        int m = s.length() + 1, n = p.length() + 1;
        int[][] dp = new int[m][n]; //s[:i]和p[:j]匹配
        dp[0][0] = 1;
        for (int i = 2; i < n; i += 2) {
            if (p.charAt(i - 1) == '*') dp[0][i] = dp[0][i - 2];
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (p.charAt(j - 1) == '*') {
                    if (dp[i][j - 2] == 1 //a  ab*
                            || (dp[i - 1][j] == 1 && s.charAt(i - 1) == p.charAt(j - 2)) // abb ab*
                            || (dp[i - 1][j] == 1 && p.charAt(j - 2) == '.')  // abb a.*

                    ) dp[i][j] = 1;
                } else {
                    if ((dp[i - 1][j - 1] == 1 && p.charAt(j - 1) == '.') // ab a.
                            || (dp[i - 1][j - 1] == 1 && p.charAt(j - 1) == s.charAt(i - 1)) //ab ab

                    ) dp[i][j] = 1;
                }
            }
        }
        return dp[m - 1][n - 1] == 1;
    }
}


推荐

如果你对本系列的其他题目感兴趣,可以参考华为OD机试真题及题解(JAVA),查看当前专栏更新的所有题目。

举报

相关推荐

0 条评论