String Concatenation (with.Java)
We’ve learned about string concatenation.
We’re going to learn about it by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.
Let’s start with the problem
Problem
You are given an array of strings, strArr.
Complete a solution function that returns the size of the largest group when the elements of strArr are grouped into strings of the same length.
Example input and output
strArr | result |
---|---|
[“a”,”bc”,”d”,”efg”,”hi”] | 2 |
My solution to the problem
import java.util.*;
class Solution {
public int solution(String[] strArr) {
int[] temp = new int[strArr.length];
for (int i = 0; i < strArr.length; i++) {
temp[i] = strArr[i].length();
}
Map<Integer, Integer> lengthCount = new HashMap<>();
for (int len : temp) {
lengthCount.put(len, lengthCount.getOrDefault(len, 0) + 1);
}
} int maxCount = 0;
for (int count : lengthCount.values()) {
if (count > maxCount) {
maxCount = count;
}
}
return maxCount;
}
Solution Description
Create a temp array: Create a temp array to store the length of each string in the string array strArr.
Create a HashMap for grouping lengths: Create a HashMap named lengthCount. This hashmap stores the string length as a key and the number of strings of that length as a value.
Grouping and counting through a loop: Iterate over the array of strings strArr, storing the length of each string in the array temp, while simultaneously checking if there is an entry in the lengthCount hashmap with length as a key, and if not, creating a new entry and initializing the value to 1. If it already exists, increment the value of that key by 1.
Calculate the maximum number of duplicates: Traverse all values (duplicates) in the lengthCount hashmap and find the maximum number of duplicates (maxCount).
Return the maximum number of duplicates: Returns the maximum number of duplicates (maxCount).