华为4.22笔试
第一题100%
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine().trim();
List<String> list = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if ('0' <= c && c <= '9') {
list.add(c + "");
}
}
Collections.sort(list);
StringBuilder sb = new StringBuilder();
for (String s : list) {
sb.append(s);
}
System.out.println(sb);
}
}
第二题80%,改了一会找不出问题遂放弃 package test;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
List<String> list=new ArrayList<>();
int fromIndex=2;
int index;
while((index=str.indexOf("5a",fromIndex+1))!=-1){
list.add("5a"+str.substring(fromIndex,index+2));
fromIndex=index+2;
}
StringBuilder sb=new StringBuilder();
for(String s:list){
String temp=s;
String[] ans=s.replaceAll("5b bb","bb").replaceAll("5b ba","ba").split(" ");
int len=Integer.parseInt(ans[ans.length-2],16);
if(len==ans.length-3){
sb.append(temp);
}
}
System.out.println(sb.toString().replaceAll("5a5a","5a"));
}
}
第三题100%,出乎我的意料,用的回溯,代码太麻烦了 package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main3 {
static List<String> result;
static int value = Integer.MIN_VALUE;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k = Integer.parseInt(sc.nextLine().split(" ")[1]);
String[] info = sc.nextLine().trim().split(" ");
List<String> list = new ArrayList<>();
for (String s : info) {
list.add(s);
}
back(list, k - 1);
StringBuilder sb=new StringBuilder();
for(String s:result){
sb.append(s+" ");
}
System.out.println(sb);
}
public static void back(List<String> list, int k) {
if (0 == k) {
int sum = 0, min = Integer.MAX_VALUE;
for (int t = 0; t < list.size(); t++) {
String s = list.get(t);
if (s != "/") {
sum += Integer.parseInt(s);
if (t == list.size() - 1) {
if (min > sum) {
min = sum;
}
}
} else {
if (min > sum) {
min = sum;
}
sum = 0;
}
}
if (min > value) {
value = min;
result = list;
}
} else {
for (int j = 1; j < list.size(); j++) {
List<String> temp = new ArrayList<>();
for (String t : list) {
temp.add(t);
}
if (!list.get(j).equals("/")) {
list.add(j, "/");
back(list, k - 1);
}
list = temp;
}
}
}
}

