My algorithm works but it is too slow.
I have to ask for help with improving this algorithm because the website which checks this, kicks me for too slow execution.
What should I improve here ?
Details:
Given a sequence of 2*k characters, please print every second character from the first half of the sequence. Start printing with the first character.
Input In the first line of input your are given the positive integer t (1<=t<=100) - the number of test cases. In the each of the next t lines, you are given a sequence of 2*k (1<=k<=100) characters.
Output For each of the test cases please please print every second character from the first half of a given sequence (the first character should appear).
Example
Input:
4 your progress is noticeable
Output:
y po i ntc
class Chars{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
if (t <= 100 && t >= 1) {
for (int i = 0; i < t; i++) {
calculate();
}
}
}
private static void calculate() {
Scanner sc = new Scanner(System.in);
String rawString = sc.nextLine();
StringBuilder afterAdd = new StringBuilder();
StringBuilder finishChars = new StringBuilder();
int numberOfChars = rawString.length();
if (numberOfChars <= 100 && numberOfChars >= 1) {
if (numberOfChars % 2 == 0) {
int numHalfChars = numberOfChars / 2;
for (int i = 0; i < numHalfChars; i++) {
afterAdd.append(rawString.charAt(i));
}
if (afterAdd.length() <= 2) {
System.out.println(afterAdd.charAt(0));
} else {
for (int i = 0; i < afterAdd.length(); i = i + 2) {
finishChars.append(afterAdd.charAt(i));
}
System.out.println(finishChars);
}
}
}
}
}
after improve:
class Algorithm{
private static List<String> results = new ArrayList<>();
public static void main (String[] args) {
calculate();
show();
}
private static void show() {
for (String result : results) {
System.out.println(result);
}
}
private static void calculate() {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
if (t <= 100 && t >= 1) {
for (int i = 0; i <= t; i++) {
String rawString = sc.nextLine();
StringBuilder finishChars = new StringBuilder();
int numberOfChars = rawString.length();
if (numberOfChars <= 100 && numberOfChars >= 1 && numberOfChars % 2 == 0) {
for (int j = 0; j < rawString.length() / 2; j = j + 2) {
finishChars.append(rawString.charAt(j));
}
results.add(String.valueOf(finishChars));
}
}
}
}
}