第39场双周赛
5550. 拆炸弹
暴力流程题:
class Solution {
public int[] decrypt(int[] code, int k) {
int n=code.length;
int []res=new int [n];
if(k==0){
for(int i=0;i<n;i++){
res[i]=0;
}
}else if(k>0){
for(int i=0;i<n;i++){
int index=i+1;
for(int j=0;j<k;j++){
if(index>=n){
index=0;
}
res[i]+=code[index++];
}
}
}else{
for(int i=0;i<n;i++){
int index=i-1;
int k1=-1*k;
for(int j=0;j<k1;j++){
if(index<0){
index=n-1;
}
res[i]+=code[index--];
}
}
}
return res;
}
}
5551. 使字符串平衡的最少删除次数
方法一:使用栈,遍历整个s字符串,如果遇到是‘b’的话,就直接入栈,否则就是‘a’,就判断如果栈不空的话,就将结果值加一,说明栈顶的一个‘b’需要弹出
class Solution {
public int minimumDeletions(String s) {
int res=0;
Stack<Character>stack=new Stack<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='b'){
stack.push('b');
}else{
if(!stack.isEmpty()){
res++;
stack.pop();
}
}
}
return res;
}
}
方法二:见代码注释
class Solution {
public int minimumDeletions(String s) {
int len=s.length();
int counta=0;//统计a的个数
int countb=0;//统计b的个数
int left=0;//作为遍历的索引
int res=0;//返回结果
//统计的过程中,如果counta的个数大于countb的个数,结果将countb的值加进去,然后将counta和countb归0,并且将left指针指向不是a的地方
while(left<len){
if(s.charAt(left)=='a'){
counta++;
}else{
countb++;
}
left++;
if(counta>countb){
res+=countb;
counta=0;
countb=0;
while(left<len&&s.charAt(left)=='a'){
left++;
}
}
}
//结果需要另外加上余下的counta的值:
res+=counta;
return res;
}
}
5552. 到家的最少跳跃次数
方法一:DFS
class Solution {
int []temp=new int [8001];
int front,back;
public int minimumJumps(int[] forbidden, int a, int b, int x) {
front=a;
back=b;
Arrays.fill(temp,Integer.MAX_VALUE);
for(int ff:forbidden){
temp[ff]=-1;
}
jump(0,0,false);
return temp[x]==Integer.MAX_VALUE?-1:temp[x];
}
//cur表示当前的位置,step表示当前走过的步数,flag表示当前是否可以往后退:true表示可以退,false表示不可以退
private void jump(int cur,int step,boolean flag){
if(cur<0||cur>8000||step>=temp[cur]){
return ;
}
temp[cur]=step;
if(flag){
jump(cur-back,step+1,false);
}
jump(cur+front,step+1,true);
}
}
方法二:BFS