1003 I want to pass! (20 points) Regular expressions (java) (solutions)

Idea: Introduce enough correct strings to find rules,   

1. PAT  ->>>  PAAT  ->>> PAAAT

2. APATA   ->>>   APAATAA    ->>>   APAAAPAAA

3.AAPATAA  ->>>   AAPAATAAAA  ->>>   AAPAAATAAAAAA

需要注意的是,要用初始正确的去推导。

发现了一个规律 ,P左边A的数量  c1  ,P T 中间A的数量 c2, T右边A的数量 c3  之间;存在数量关系  c1*c2==c3;

 


import java.util.ArrayList;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        int flagSum = 0;
        ArrayList<String> stringList = new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        flagSum = Integer.parseInt(sc.nextLine());
        for (int i = 0; i < flagSum; ++i) {
            stringList.add(sc.nextLine());
        }
        // 判断
        for (String x : stringList) {
            judge(x);
        }
    }
    public static void judge(String s) {
        String pattern = "A*PA+TA*";//推导式
        String pattern1 = "PA+T";//对应A数量的第一项正确项
        if (s.matches(pattern)) {
            if (s.matches(pattern1)) {
                System.out.println("YES");
            } else {
                String temp[] = s.split("P|T");
                int aLength = temp[0].length();
                int bLength = temp[1].length();
                int cLength = temp[2].length();
                if (aLength*bLength==cLength) {
                    System.out.println("YES");
                } else {
                    System.out.println("NO");
                }
            }
        } else {
            System.out.println("NO");
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_41048982/article/details/109323354
Recommended