一、3502. 到达每个位置的最小费用
题目链接
本题是一道脑筋急转弯,实际就是计算前缀最小值,画个图理解一下:
代码如下:
class Solution {
public int[] minCosts(int[] cost) {
int n = cost.length;
int[] ans = new int[n];
ans[0] = cost[0];
for(int i = 1; i < n; i++){
ans[i] = Math.min(ans[i-1], cost[i]);
}
return ans;
}
}
二、3503. 子字符串连接后的最长回文串 I
题目链接
本题数据范围较小,直接暴力,代码如下:
class Solution {
public int longestPalindrome(String s, String t) {
int n = s.length();
int m = t.length();
int ans = 1;
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
if(check(s.substring(i,j+1))){
ans = Math.max(ans, j-i+1);
}
for(int x = 0; x < m; x++){
for(int y = x; y < m; y++){
if(check(s.substring(i,j+1) + t.substring(x,y+1))){
ans = Math.max(ans, j-i+1+y-x+1);
}
if(check(t.substring(x,y+1))){
ans = Math.max(ans, y-x+1);
}
}
}
}
}
return ans;
}
boolean check(String s){
int l = 0, r = s.length() - 1;
while(l < r){
if(s.charAt(l) != s.charAt(r))
return false;
l++;
r--;
}
return true;
}
}
三、3504. 子字符串连接后的最长回文串 II
题目链接
本题要构造一个最长的回文串,可以将它分成三个部分 —— ABA,它有两种情况:
- 情况一:
s = "???AB??", t = "???A??"
,A1 与 A2 互相回文,B 自身是一个回文串 - 情况二:
s = "???A???", t = "??BA??"
,A1 与 A2 互相回文,B 自身是一个回文串 - 注:A,B 长度都可以为 0
举一个例子 s = "???abcac??", t = "???ba??"
,这里 A1 = “ab”,B = “cac”,A2 = “ba”,可以将它拆分成两个部分:
- A1 与 A2,这里换一个视角,将 A2 翻转过来,A1 就等于 A2,所以可以将
字符串t
反转一下,这部分实际上就变成了一个求s 与 resT
的最长公