** 软开中心是核心代码模式
第一题
字符串
找到两个字符串中相同的字符用*代替,输出第一个字符串替换后的字符串
// 遍历第一个字符串,对每个字符检查是否在第二个字符串出现过
public String replace (String mystring1, String mystring2) {
for (int i = 0; i < mystring1.length(); i++) {
String ch = String.valueOf(mystring1.charAt(i));
if(mystring2.contains(ch)) {
mystring1 = mystring1.replace(ch, "*");
}
}
return mystring1;
}
第二题
链表
给出一个大小为n的链表a,每次将链表的第二个数添加到链表末尾,并删除链表的前三个数,直到表里不足三个数返回这个链表
/**
* Definition for a ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) { this.val = val; }
* }
*/
public ListNode delete (ListNode a) {
//不足三个数时返回
if (a == null || a.next == null || a.next.next == null) {
return a;
}
//创建虚拟头节点
ListNode dummy = new ListNode(0);
dummy.next = a;
ListNode tail = a;
//尾节点后面添加了节点,要将尾节点后移
while (tail.next != null) {
tail = tail.next;
}
//每次将链表的第二个数添加到链表末尾,并删除链表的前三个数
while (dummy.next != null && dummy.next.next != null && dummy.next.next.next != null &&) {
tail.next = new ListNode(dummy.next.next.val);
tail = tail.next;
dummy.next = dummy.next.next.next.next;
}
tail.next = null;
return dummy.next;
}
第三题
字符串
字符串只包括数字或者字符“-”,对字符串进行排序,找到能组成的最小整数,例如:输入-3012,输出-3210;输入3012,输出1023
public String question3(String mystring) {
boolean flag = mystring.contains("-");
int count0 = 0;
for (int i = 0; i < mystring.length(); i++) {
if(mystring.charAt(i) == '0') {
count0++;
}
}
//去掉负号和0
mystring = mystring.replace("0", "");
mystring = mystring.replace("-", "");
char[] chars = mystring.toCharArray();
Arrays.sort(chars);
String res = new String(chars);
if(!flag) {
res = res.substring(0, 1) + "0".repeat(count0) + res.substring(1);
} else {
res = "-";
//倒叙
for (int i = 0; i < chars.length; i++) {
res += chars[chars.length - 1 - i];
}
res += "0".repeat(count0);
}
return res;
}
}
第四题
字符串
字符串只包括数字和字符“+”“-”,找到一个最大的n,使得字符串的前n个字符组成的算式是合法算式,例如输入12+34-,输出6,最长的合法算式是-12 + 34,长度为6
public String question4(String mystring) {
boolean flag = mystring.contains("-");
int count0 = 0;
for (int i = 0; i < mystring.length(); i++) {
if(mystring.charAt(i) == '0') {
count0++;
}
}
//去掉负号和0
mystring = mystring.replace("0", "");
mystring = mystring.replace("-", "");
char[] chars = mystring.toCharArray();
Arrays.sort(chars);
String res = new String(chars);
if(!flag) {
res = res.substring(0, 1) + "0".repeat(count0) + res.substring(1);
} else {
res = "-";
//倒叙
for (int i = 0; i < chars.length; i++) {
res += chars[chars.length - 1 - i];
}
res += "0".repeat(count0);
}
return res;
}
}