(UVA) Wedding of Sultan - Solution
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=666&page=show_problem&problem=4027
import java.io.*;
import java.util.*;
class Main {
public Deque<Character> trails;
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int numTests = sc.nextInt();
for (int test = 0; test < numTests; test++) {
String seq = sc.next();
char start = seq.charAt(0);
trails = new ArrayDeque<>();
int[] count = new int[26];
for (int i = 0; i < seq.length(); i++) {
if (trails.peek() != null && trails.peek() == seq.charAt(i)) {
count[seq.charAt(i)-'A']++;
trails.poll();
if (trails.peek() == null) {
continue;
}
char c = trails.peek();
count[c-'A']++;
} else {
trails.addFirst(seq.charAt(i));
}
}
bw.write("Case " + (test+1) + "\n");
for (int i = 0; i < 26; i++) {
if (count[i] == 0) {
continue;
}
if ((char)(i+'A') == seq.charAt(0)) {
bw.write((char)(i+'A') + " = " + (count[i]-1) + "\n");
continue;
}
bw.write((char)(i+'A') + " = " + count[i] + "\n");
}
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
import java.io.*;
import java.util.*;
class Main {
public Deque<Character> trails;
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int numTests = sc.nextInt();
for (int test = 0; test < numTests; test++) {
String seq = sc.next();
char start = seq.charAt(0);
trails = new ArrayDeque<>();
int[] count = new int[26];
for (int i = 0; i < seq.length(); i++) {
if (trails.peek() != null && trails.peek() == seq.charAt(i)) {
count[seq.charAt(i)-'A']++;
trails.poll();
if (trails.peek() == null) {
continue;
}
char c = trails.peek();
count[c-'A']++;
} else {
trails.addFirst(seq.charAt(i));
}
}
bw.write("Case " + (test+1) + "\n");
for (int i = 0; i < 26; i++) {
if (count[i] == 0) {
continue;
}
if ((char)(i+'A') == seq.charAt(0)) {
bw.write((char)(i+'A') + " = " + (count[i]-1) + "\n");
continue;
}
bw.write((char)(i+'A') + " = " + count[i] + "\n");
}
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment