-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNeedleHay.java
More file actions
65 lines (50 loc) · 1.76 KB
/
NeedleHay.java
File metadata and controls
65 lines (50 loc) · 1.76 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
59
60
61
62
63
64
65
import java.io.*;
import java.util.*;
public class NeedleHay {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String line = br.readLine();
if (line == null) return;
int T = Integer.parseInt(line.trim());
while (T-- > 0) {
String s = br.readLine();
String t = br.readLine();
if (s == null || t == null) break;
solve(s.trim(), t.trim(), out);
}
out.flush();
}
private static void solve(String s, String t, PrintWriter out) {
int[] sCount = new int[26];
int[] tCount = new int[26];
for (char c : s.toCharArray()) sCount[c - 'a']++;
for (char c : t.toCharArray()) tCount[c - 'a']++;
int[] extras = new int[26];
for (int i = 0; i < 26; i++) {
if (tCount[i] < sCount[i]) {
out.println("Impossible");
return;
}
extras[i] = tCount[i] - sCount[i];
}
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
int charIndex = c - 'a';
for (int i = 0; i < charIndex; i++) {
while (extras[i] > 0) {
sb.append((char)('a' + i));
extras[i]--;
}
}
sb.append(c);
}
for (int i = 0; i < 26; i++) {
while (extras[i] > 0) {
sb.append((char)('a' + i));
extras[i]--;
}
}
out.println(sb.toString());
}
}