Introduction

Hello and welcome to our exciting exploration of Java strings! For today's lesson, we've prepared something extraordinarily interesting: you will learn how to access characters from a string following a distinctive pattern. Our presentation is both comprehensive and concise, allowing you to master the concept promptly. Let's get started!

Task Statement

Imagine this: You receive a string, from which you need to extract characters. However, the sequence in which you select them diverges from the norm. You start with the first character, then select the last character, move to the second character, then choose the second-to-last character, and continue this pattern until there are no characters left. Quite a mind-bender, isn't it?

Here's what we mean:

You are required to craft a Java function, public static String solution(String inputString) { ... } in the Solution class. This function takes inputString as a parameter, a string of lowercase English alphabet letters ('a' to 'z'), with a length ranging between 1 to 100 characters. The function then returns a new string, fashioned from the input string but with characters selected in the pattern we described above.

For example, if the inputString is "abcdefg", the function should return "agbfced".

Solution Building: Step 1 - Initialization

Before we delve into the problem-solving aspect, let's arrange our result store. We initiate a variable, result, as an empty StringBuilder to stockpile the output.

public class Solution {
    public static String solution(String inputString) {
        StringBuilder result = new StringBuilder();
Step 2 - Looping over the string

Upon initialization, we need to traverse the inputString. Java furnishes a for loop to iterate over all elements in a string efficiently.

Now, the question arises: What is the requisite number of iterations for our loop? Given that we select two characters per iteration — one from the beginning and one from the end — we need the loop to run for half of the string's length if the length is even, or half the length plus one if it's odd to include the middle character.

We can realize this by employing inputString.length() / 2 + inputString.length() % 2. This ensures that the loop iterates for half the length if it is even and half the length plus one if it's odd.

Here's our function thus far:

public class Solution {
    public static String solution(String inputString) {
        StringBuilder result = new StringBuilder();
        int length = inputString.length();
        for (int i = 0; i < length / 2 + length % 2; i++) {
            // Implementation in next step
        }
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal