AcWing 3160. 拉马车
原题链接
简单
作者:
看着我
,
2021-03-27 10:17:06
,
所有人可见
,
阅读 422
Java 代码
public class Main{
public static void main(String[] args){
LinkedList<Character> a = new LinkedList<>();
LinkedList<Character> b = new LinkedList<>();
LinkedList<Character> c = new LinkedList<>();
//出牌顺序,A为true,B为false
boolean flag = true;
start(a, b);
//保存源牌组的字符串序列
String srcA = replaceToString(a);
String srcB = replaceToString(b);
while (!a.isEmpty() && !b.isEmpty()) {
LinkedList<Character> tem = new LinkedList<>();
//a出牌
if (flag) {
char target = a.removeFirst();
c.add(target);
tem = get(c, target);
a.addAll(tem);
} else {//b出牌
char target = b.removeFirst();
c.add(target);
tem = get(c, target);
b.addAll(tem);
}
//获取当前牌组字符串序列
String temA = replaceToString(a);
String temB = replaceToString(b);
//判断当前字符串是否与源字符串相同,若相同则说明本局永远不会结束,输出-1结束程序
if (srcA.contentEquals(temA) && srcB.contentEquals(temB)) {
System.out.println(-1);
System.exit(0);
}
//本局没有赢家,换人出牌
if (tem.isEmpty()) {
flag = !flag;
}
}
//输出不为空的牌组
if (b.isEmpty()) {
System.out.println(replaceToString(a));
} else {
System.out.println(replaceToString(b));
}
}
//获取牌相同之间的牌
private static LinkedList<Character> get(LinkedList<Character> c, char target) {
LinkedList<Character> tem = new LinkedList<>();
int index = c.indexOf(target);
int n = c.size();
if (index >= 0 && index != n-1) {
for (int i = 0; i < n - index; i++) {
tem.add(c.removeLast());
}
}
return tem;
}
//将字符集合转化为字符串
public static String replaceToString(LinkedList<Character> target) {
StringBuilder sb = new StringBuilder();
for (Character character : target) {
sb.append(character);
}
return sb.toString();
}
//初始化
public static void start(LinkedList<Character> a, LinkedList<Character> b) {
Scanner sc = new Scanner(System.in);
char[] astr = sc.nextLine().toCharArray();
char[] bstr = sc.nextLine().toCharArray();
int n = astr.length;
for (int i = 0; i < n; i++) {
a.add(astr[i]);
b.add(bstr[i]);
}
}
}