【蓝桥杯2017Java】方格分割、正则问题

方格分割

在这里插入图片描述
联想到剪邮票那道题,但是这个题目方格较多,30选15时间太久,所以舍弃那种方法。现在的思路是,以(3,3)坐标为中心向四周扩散,剪邮票是选格子,而本题是要以走过的路线作为格子的分割线,怎么分割方格呢,我们能注意到分割好之后的方格是以(3,3)中心对称的,所以我们在dfs深搜到某个点的时候应该也把该点中心对称的点也给标记了,这样分割的两个方格才是中心对称的。还有最后得到的总数要除以4,因为这个方格是水平竖直对称的。

public class Main {
    static int dir[][] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
    static int vis[][]=new int[7][7];
    static int ans = 0;
    public static void dfs(int x, int y){
        if(x == 0 || y == 0 || x == 6 || y == 6){//到边界的时候返回
            ans++;
            return ;
        }
        for(int i = 0; i < 4; i++){//向四个方向搜索移动
            int x1 = x + dir[i][0];
            int y1 = y + dir[i][1];

            int x2 = 6 - x1; 
            int y2 = 6 - y1;

            if(x1 >= 0 && y1 >= 0 && x1 <= 6 && y1 <= 6){
                if(vis[x1][y1]!=1){//回溯
                    vis[x1][y1] = vis[x2][y2] = 1;
                    dfs(x1,y1);
                    vis[x1][y1] = vis[x2][y2] = 0;
                }
            }
        }
    }
    public static void main(String[] args) {
        vis[3][3] = 1;
        dfs(3,3);
        System.out.println(ans/4);
    }
}

答案509


正则问题

在这里插入图片描述

关于题目的解释

一开始我也没明白,下方这个为什么是6呢。按照运算来,比如下方的这个,找好括号的对应,看步骤一步一步来就理解了,下图二

在这里插入图片描述

在这里插入图片描述

思路

用dfs。遇到的字符有以下的情况处理。

  • ( 开始一段
  • x 长度+1
  • | 保存临时的长度
  • )结算一段,返回临时的和之前长度的较大值

代码

class Main{
    public static int len;
    public static int pos;
    public static String s;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        s=scanner.nextLine();
        len=s.length();
        int ans=f();
        System.out.println(ans);
        scanner.close();
    }

    /*求出当前字符串,自当前下标到结束能匹配的字符串的长度*/
    public static int f(){
        int ans=0;
        int temp=0;//用于保存连续的x的数量
        while (pos<len){
            if(s.charAt(pos)=='('){
                pos++;
                temp+=f();//等待后面的结果并累加到ans
            }else if(s.charAt(pos)=='x'){
                pos++;
                temp++;
            }else if(s.charAt(pos)=='|'){
                pos++;
                ans=Math.max(ans,temp);
                temp=0;
            }else if (s.charAt(pos)==')'){
                pos++;
                return Math.max(ans,temp);
            }
        }
        return Math.max(ans,temp);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值