-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMorganAndAString.java
More file actions
58 lines (50 loc) · 1.86 KB
/
MorganAndAString.java
File metadata and controls
58 lines (50 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.*;
public class MorganAndString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
in.nextLine();
while(t-- > 0) {
String A = in.nextLine();
String B = in.nextLine();
int i = 0, j = 0;
StringBuffer sb = new StringBuffer();
while(i < A.length() && j < B.length()) {
if (A.charAt(i) < B.charAt(j)) {
sb.append(A.charAt(i++));
} else if (A.charAt(i) > B.charAt(j)) {
sb.append(B.charAt(j++));
} else {
int x = i, y = j;
char a = A.charAt(i);
for(; x < A.length() && y < B.length(); x++, y++) {
if (A.charAt(x) != B.charAt(y)) {
break;
} else if (A.charAt(x) > a) {
sb.append(A.substring(i, x)).append(B.substring(j, y));
i = x; j = y;
a = A.charAt(x);
}
}
if (x == A.length()) {
sb.append(B.charAt(j));
j++;
} else if (y == B.length()) {
sb.append(A.charAt(i));
i++;
} else {
if (A.charAt(x) < B.charAt(y)) {
sb.append(A.charAt(i));
i++;
} else {
sb.append(B.charAt(j));
j++;
}
}
}
}
sb.append(A.substring(i)).append(B.substring(j));
System.out.println(sb);
}
}
}