1.牛牛冲钻五
题目链接:A-牛牛冲钻五_牛客小白月赛38
题目描述:
代码如下:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
int t=scanner.nextInt();
while(t--!=0){
int n=scanner.nextInt();
int k=scanner.nextInt();
int ret=0;
char[] s=scanner.next().toCharArray();
for(int i=0;i<s.length;i++){
if(s[i]== 'L'){
ret-=1;
}else{
if(i-1>=0 && i-2>=0 && s[i-1]=='W' && s[i-2]=='W'){
ret+=k;
}else{
ret+=1;
}
}
}
System.out.println(ret);
}
}
}
2.最长无重复子数组
题目链接:最长无重复子数组_牛客题霸_牛客网
题目描述:
判断是否是重复的话,可以使用哈希表,但是要注意时间复杂度
代码如下:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
int ret=0;
int[] hash=new int[100010];
int right =0;
int left=0;
while(right<arr.length){
hash[arr[right]]++;
while(hash[arr[right]]>1){
hash[arr[left]]--;
left++;
}
ret=Math.max(ret,right-left+1);
right++;
}
return ret;
}
}
3.小红的字符串重排
注:如果相同字母的个数大于总数的一半,则不满足条件。
代码如下:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
char[] s = scanner.next().toCharArray();
scanner.close();
char maxChar = '0';
int maxCount = 0;
int[] hash = new int[26];
for (int i = 0; i < s.length; i++) {
char ch = s[i];
hash[ch - 'a']++;
if (hash[ch - 'a'] > maxCount) {
maxChar = ch;
maxCount = hash[ch - 'a'];
}
}
if (maxCount > (n + 1) / 2) {
System.out.println("no");
} else {
System.out.println("yes");
char[] ret = new char[n];
int i = 0;
// 先填充最多的字符
while (maxCount-- > 0) {
ret[i] = maxChar;
i += 2;
}
// 填充其他字符
for (int j = 0; j < 26; j++) {
if (hash[j] > 0 && (char) (j + 'a') != maxChar) {
while (hash[j]-- > 0) {
if (i >= n) i = 1; // 如果偶数位填满,从奇数位开始
ret[i] = (char) (j + 'a');
i += 2;
}
}
}
// 输出结果
System.out.println(new String(ret));
}
}
}
希望能对大家有所帮助!!!