r/programminghelp • • May 16 '24
Java Hey, I was trying out a question on leetcode of Group Anagrams
import java.util.*;
public class Anagrams { public static void main(String[] args) { List<String> str=new ArrayList<>(); str.add(""); str.add(""); str.add(""); str.add(""); str.add(""); List<List<String>> group=new ArrayList<>(); group=checkAnagram(str); System.out.println(group); }
public static List<List<String>> checkAnagram(List<String> str)
{
List<List<String>> ana=new ArrayList<>();
for (int i = 0; i < str.size(); i++)
{
ana.add(new ArrayList<String>());
ana.get(i).add(str.get(i));
}
for (int i = 0; i < ana.size(); i++)
{
int k = i;
while(k < ana.size())
{
if (check(ana.get(i).get(0), ana.get(k+1).get(0)))
{
ana.get(i).add(ana.get(k+1).get(0));
ana.remove(k+1);
}
k++;
}
}
return ana;
}
public static boolean check(String firstStr, String secondStr)
{
char[] first = firstStr.toCharArray();
char[] second = secondStr.toCharArray();
Arrays.sort(first);
Arrays.sort(second);
return Arrays.equals(first, second);
}}
It's giving out of bounds error. The output should give all empty strings in first sublist of the 2d list. I don't want a new solution, I want to know how to solve this issue.
1
Upvotes
1
u/sepp2k May 16 '24
Where and when does the out of bounds error happen? What's the value of the index and the size of the collection at that point?
1
u/DDDDarky May 16 '24
This looks like it has a lot of error potential, what happens if your k = ana.size() - 1?