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];
}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章