Contents

Create with l (with.Java)

   Dec 6, 2023     1 min read

This is the “Make it L” problem.

We’re going to learn about it by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them.

Let’s start with the problem.

Problem

You are given a string, myString, consisting of lowercase letters of the alphabet.

Complete the solution function to return a string that replaces all characters that precede “l” in the alphabetical order with “l”.

Example input and output

myStringresult
“abcdevwxyz”“lllllvwxyz”
“jjnnllkkmm”“llnnllllmm”

My solution to the ### problem

class Solution {
    public static String solution(String myString) {
        char[] charArray = myString.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            if (charArray[i] < 'l') {
                charArray[i] = 'l';
            }
        }
    } return new String(charArray);
}

solution

char[] charArray = myString.toCharArray();: Converts the input string myString to the character array charArray. This allows us to access the string on a character-by-character basis.

for (int i = 0; i < charArray.length; i++) : Iterate through the character array charArray, performing an action on each character.

if (charArray[i] < ‘l’) : If the current character is a character that is lexicographically ahead of ‘l’:

Replace that character with ‘l’.

return new String(charArray);: Convert the changed character array charArray back to a string and return it.