Length of array elements (with. Java)
This is an article that looks into the ālength of array elementsā issue.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Letās look at the problem first.
problem
A string array strlist is given as a parameter.
Complete the solution function to retrun an array containing the length of each element of strlist.
Restrictions
- 1 ā¤ length of strlist element ā¤ 100
- strlist consists of lowercase letters, uppercase letters, and special characters.
Input/Output Example
strlist | result |
---|---|
[āWeā, āareā, ātheā, āworld!ā] | [2, 3, 3, 6] |
[āIā, āLoveā, āProgrammers.ā] | [1, 4, 12] |
My solution to the problem
class Solution {
public int[] solution(String[] strlist) {
int[] answer = new int[strlist.length];
int count = 0;
for(String temp : strlist){
answer[count++] = temp.length();
}
return answer;
}
}
Solution explanation
- Array initialization: Initialize the array answer to store the result as long as the given string array strlist through int[] answer = new int[strlist.length];
- Calculating string length: While iterating through the array strlist using a for-each statement, calculate the length of each string with temp.length() and store it in the answer array at the corresponding index.
- Index increase: After storing the length of each string, the count variable is increased so that the value can be stored at the next index.
- Result return: Calculate the length of all strings, store them in an array, and finally return the result array answer.
Code Advantages
- Simple logic: It consists of simple yet efficient logic that calculates the length of the string.
- Scalability: Array initialization is performed dynamically so that it can respond flexibly according to the length of the array, making it possible to respond to a variety of inputs.
Code Disadvantages
- Lack of error handling: The current code does not consider exception handling, such as when the input array is null. It is a good idea to add appropriate exception handling.
- Fixed return value data type: The current code returns the result array as int[], but there is a lack of logic to respond when various data types are required depending on the input. There is a need to improve it by considering the diversity of inputs and returns.