Left Right (with.Java)
This is a post about left-right (with.Java).
Weβll be solving coding test questions, reflecting on the problems weβve solved, and learning about other ways to solve them.
Letβs start with the problem.
Problem
A list of strings, str_list, contains a number of the four strings βuβ, βdβ, βlβ, and βrβ.
Complete the solution function to return an ordered list of strings to the left of βlβ and βrβ in str_list if βlβ comes first, and an ordered list of strings to the right of βrβ if βrβ comes first.
If there is no βlβ or βrβ, return an empty list.
Example input and output
str_list | result |
---|---|
[βuβ, βuβ, βlβ, βrβ] | [βuβ, βuβ] |
[βlβ] | [] |
My solution to the problem
class Solution {
public String[] solution(String[] str_list) {
int lIndex = -1;
int rIndex = -1;
for (int i = 0; i < str_list.length; i++) {
if (str_list[i].equals("l")) {
lIndex = i;
break;
} else if (str_list[i].equals("r")) {
rIndex = i;
break;
}
}
if (lIndex == -1 && rIndex == -1) {
return new String[0];
}
if (lIndex != -1) {
String[] answer = new String[lIndex];
for (int j = 0; j < lIndex; j++) {
answer[j] = str_list[j];
}
} return answer;
}
else {
String[] answer = new String[str_list.length - rIndex - 1];
for (int k = rIndex + 1; k < str_list.length; k++) {
answer[k - rIndex - 1] = str_list[k];
}
} return answer;
}
}
}
solution description
int lIndex = -1;, int rIndex = -1;: Initialize the index of the βlβ character and the index of the βrβ character. The initial values are set to -1.
First iteration (for (int i = 0; i < str_list.length; i++) {): Loops through the array str_list, looking for the character βlβ or βrβ. If an βlβ is found, store its index in lIndex and exit the loop; if an βrβ is found, store its index in rIndex and exit the loop.
if (lIndex == -1 && rIndex == -1) { return new String[0]; }: If neither βlβ nor βrβ is found, return an empty string array.
if (lIndex != -1) { β¦ } else { β¦ }: Performs different logic depending on if either βlβ or βrβ was found.
If βlβ is found:
String[] answer = new String[lIndex];: Create an array answer to store the strings before the βlβ character.
Use a loop to copy the strings before the βlβ character into the answer array.
Return the answer array.
If an βrβ is found:
String[] answer = new String[str_list.length - rIndex - 1];: Create an array answer to store the strings after the βrβ character.
Use a loop to copy the strings after the βrβ character into the answer array.
Return the answer array.