Leet Code 第 131 场周赛

5016. 删除最外层的括号

题目链接

题解:用栈处理括号匹配

代码:

class Solution {
    public String removeOuterParentheses(String S) {
          Stack<Character> stack = new Stack<Character> ();
         String ans = new String();
         for(int i = 0; i < S.length(); i++)
         {
             if(S.charAt(i) =='(' ) {
            	 if(stack.size() != 0) ans += '(';
            	 stack.push('(');
             }
             else {
            	 stack.pop();
            	 if(stack.size() != 0) ans += ')';
             }
         }
         return ans;
    }
}

5017. 从根到叶的二进制数之和

题目链接

题解: 直接DFS即可

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private static int mod = (int)Math.pow(10,9)+7;
    private static int Dfs(TreeNode r, int x)
	 {
		if(r == null) return 0;
        if(r.left == null && r.right == null) return (x*2 + r.val)%(mod);
		else return (Dfs(r.left, (x*2+r.val)%(mod)) + Dfs(r.right, (x*2+r.val)%(mod)))%(mod);
	 }
    public int sumRootToLeaf(TreeNode root) {
         return Dfs(root, 0)%(mod);
    }
}

5018. 驼峰式匹配

题目链接

题解: 扫描对于每一个字符串与母串进行匹配即可

代码:

class Solution {
    public List<Boolean> camelMatch(String[] queries, String pattern) {
         List<Boolean> ans = new LinkedList<Boolean>(); 
	   for(int i = 0; i < queries.length; i++)
        {
        	boolean res = true;
        	int k = 0;
        	//System.out.println(queries.length);
        	for(int j = 0; j < queries[i].length(); j++)
        	{
        		if(k < pattern.length() && queries[i].charAt(j) == pattern.charAt(k)) 
        			{
        			k++;
        			continue;
        			}
        		else if(Character.isLowerCase(queries[i].charAt(j))) continue;
        		else {res = false;break;}
        	}
        	if(k != pattern.length()) res = false;
        	ans.add(res);
        }
	   return ans;
    }
}

5019. 视频拼接

题目链接

题解: 

动态规划,先预处理数据,a[i] 表示:从i开始的最长区间的右端点下标,例如有两个区间[5,10],[5,20], 则a[5] = 10;

状态转移方程为:dp[i] = min(dp[i],dp[j]+1)   (a[j] > i, 0<= j <= i)  dp[i]表示覆盖区间 [1,i]所需要的最小区间数。

代码: 

class Solution {
    public int videoStitching(int[][] clips, int T) {
        int n = clips.length;
        int a[] = new int[110];
        int dp[] = new int[110];
        Arrays.fill(a,-1);
        Arrays.fill(dp,110);
        for(int i = 0; i < n; i++)
            a[clips[i][0]] = Math.max(a[clips[i][0]],clips[i][1]);
        dp[0] = 0;
        for(int i = 0; i <= T; i++)
            for(int j = 0; j <= i; j++)
                if(a[j] >= i) dp[i] = Math.min(dp[i],dp[j]+1);
        if(dp[T] >= 110) return -1;
        else return dp[T];
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值