2024/9/26 Hot100 dp结束,以及今日的每日一题

This commit is contained in:
linlihong 2024-09-26 16:14:24 +08:00
parent 3a82396c07
commit a5035ff16f
3 changed files with 143 additions and 0 deletions

View File

@ -0,0 +1,70 @@
package com.cool.hot100.dp;
import java.util.Stack;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/26/13:53
* DayNumber 3
* Hard 3
* Level 7
* @Description 32. 最长有效括号
* @Link https://leetcode.cn/problems/longest-valid-parentheses/description/?envType=study-plan-v2&envId=top-100-liked
*/
public class Num31 {
/**
* 栈解法
*
* @param s
* @return
*/
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int res = 0;
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.empty()) {
stack.push(i);
} else {
res = Math.max(res, i - stack.peek());
}
}
}
return res;
}
/**
* 动态规划解法
* @param s
* @return
*/
public int longestValidParentheses2(String s) {
int max = 0;
s = "a " + s;
int[] dp = new int[s.length()];
for (int i = 2; i < s.length(); i++) {
if (s.charAt(i) == ')') {
//s.charAt(i - dp[i - 1] - 1) == '('是在校验当前已组成有效括号的前一个括号是否为(,
max = Math.max(max, dp[i]);
if (s.charAt(i - 1) == ')') {
if (s.charAt(i - dp[i - 1] - 1) == '(') {
dp[i] = dp[i - 1] + 2 + dp[i - dp[i - 1] - 2];
}
} else if (s.charAt(i - dp[i - 1] - 1) == '(') {
/*i-2-dp[i-1]为当前已经组成有效括号的前一个括号,这里的有效括号与
上面的有效括号不同这里是算上当前括号的有效括号用来应对()(())这样的数据*/
dp[i] = dp[i - 2 - dp[i - 1]] + 2 + dp[i - 1];
}
}
}
return max;
}
}

View File

@ -0,0 +1,45 @@
package com.cool.hot100.dp;
import org.junit.Test;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/26/09:31
* DayNumber 1
* Hard 2
* Level ?
* @Description 416. 分割等和子集
* @Link https://leetcode.cn/problems/partition-equal-subset-sum/description/?envType=study-plan-v2&envId=top-100-liked
*/
public class Num416 {
public boolean canPartition(int[] nums) {
int average = 0;
for (int num : nums) {
average += num;
}
if ((average & 1) == 1) {
return false;
}
average = average / 2;
boolean[] dp = new boolean[average + 1];
if (nums[0] <= average) {
dp[nums[0]] = true;
}
for (int i = 1; i < nums.length; i++) {
for (int j = average; nums[i] <= j; j--) {
dp[j] = dp[j] || dp[j - nums[i]];
if (dp[average]) {
return true;
}
}
}
return dp[average];
}
@Test
public void test(){
canPartition(new int[]{1,2,5});
}
}

View File

@ -0,0 +1,28 @@
package com.cool.one_question_per_day;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/26/11:33
* DayNumber 2
* Hard 1
* Level ?
* @Description 2535. 数组元素和与数字和的绝对差
* @Link https://leetcode.cn/problems/difference-between-element-sum-and-digit-sum-of-an-array/description/?envType=daily-question&envId=2024-09-26
*/
public class LeetCode20240926 {
public int differenceOfSum(int[] nums) {
int sum=0;
int sum1=0;
for(int num:nums){
sum+=num;
while(num!=0){
sum1+=num%10;
num=num/10;
}
}
return Math.abs(sum1-sum);
}
}