376. 摆动序列
题目链接:https://leetcode.cn/problems/wiggle-subsequence/description/
这个题目自己首先想到的是动态规划解题,贪心解法真的非常妙,参考下面题解:https://leetcode.cn/problems/wiggle-subsequence/solutions/284327/tan-xin-si-lu-qing-xi-er-zheng-que-de-ti-jie-by-lg/
代码:
class Solution {
public int wiggleMaxLength(int[] nums) {
int len = nums.length;
int up = 1, down = 1;
for(int i = 1; i < len; i++){
if(nums[i] > nums[i - 1]){
up = down + 1;
}else if(nums[i] < nums[i - 1]){
down = up + 1;
}
}
return len == 0 ? 0 : Math.max(up, down);
}
}
409. 最长回文串
题目链接:https://leetcode.cn/problems/longest-palindrome/?envType=study-plan-v2&envId=2024-spring-sprint-100
1.使用哈希表解题:由于题目说明只包含大小写字母,所以构建两个int[] arr = new int[26],一个用于存储大小字母,一个用于存储小写字母。
2.遍历过程中,如果某个字符,在对应大、小写哈希表中出现过,则将返回结果 +2,同时将哈希表中对应值置0。
3.字符串遍历结果后,需要确认哈希表中是否存在值为1的元素,如果存在,则结果+1,直接返回结果,不存在,结果不+1,直接返回。
代码如下:
class Solution {
public int longestPalindrome(String s) {
int[] lowerDig = new int[26];
int[] upperDig = new int[26];
int ans = 0;
for(char ch : s.toCharArray()){
if(ch >= 'a' && ch <= 'z'){
if(lowerDig[ch - 'a'] == 1){
lowerDig[ch - 'a']--;
ans += 2;
}else{
lowerDig[ch - 'a']++;
}
}else{
if(upperDig[ch - 'A'] == 1){
upperDig[ch - 'A']--;
ans += 2;
}else{
upperDig[ch - 'A']++;
}
}
}
for(int i = 0; i < 26; i++){
if(lowerDig[i] == 1){
++ans;
return ans;
}else if(upperDig[i] == 1){
++ans;
return ans;
}
}
return ans;
}
}
455. 分发饼干
题目链接:https://leetcode.cn/problems/assign-cookies/description/?envType=study-plan-v2&envId=2024-spring-sprint-100
感觉挺简单的,不愧是简单题,代码:
class Solution {
public int findContentChildren(int[] g, int[] s) {
int lenG = g.length, lenS = s.length;
Arrays.sort(g);
Arrays.sort(s);
int ans = 0;
for(int gi = 0, si = 0; gi < lenG && si < lenS;){
if(s[si] >= g[gi]){
++ans;
++gi;
}
++si;
}
return ans;
}
}