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