Algorithms - letter word grouping ectopic
Given a string array, ectopic word letters together. Ectopic word letters refer to the same letters, but arranged in different strings.
Example:
Input: [ "eat", "tea ", "tan", "ate", "nat", "bat"],
Output:
[
[ "ATE", "EAT", "TEA"],
[ "NAT", "Tan"],
[ "BAT"]
]
Source: stay button (LeetCode)
import java.util.*;
public class GroupAnagram {
public static void main(String[] args){
String[] input = new String[6];
input[0] = "eat";
input[1] = "tea";
input[2] = "tan";
input[3] = "ate";
input[4] = "nat";
input[5] = "bat";
System.out.println(groupAnagrams(input));
}
public static String order(String input){
String result = "";
char[] str = input.toCharArray();
for(int i = 1; i<str.length;i++){
for(int j=0; j<str.length-1;j++){
if(str[j]>str[i]){
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
result = String.valueOf(str);
return result;
}
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<List<String>>();
for(int i = 0; i<strs.length; i++){
String change = order(strs[i]);
if(result.size() == 0){
List<String> inner = new ArrayList<String>();
inner.add(strs[i]);
result.add(inner);
}
else{
String flag = "not";
for(int j = 0; j<result.size();j++){
if(order(result.get(j).get(0)).equals(change)){
result.get(j).add(strs[i]);
flag = "have";
}
}
if(flag.equals("not")){
List<String> addition = new ArrayList<>();
addition.add(strs[i]);
result.add(addition);
}
}
}
return result;
}
}