Skip to content
This repository has been archived by the owner on Oct 4, 2023. It is now read-only.

Create StringAnagramsList.java #48

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Java/StringAnagramsList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
public class StringAnagramsList {

public static void main(String[] args) {
String str = "cat tac atc dog god";
String[] arr = str.trim().split(" ");

HashMap<String, List<String>> hashMap = new HashMap<>();
for (String item : arr) {
String key = getSortedItem(item);
List<String> listItems = hashMap.get(key);
if (listItems == null) {
listItems = new ArrayList<>();
}
listItems.add(item);
hashMap.put(key, listItems);
}
System.out.println(new ArrayList<>(hashMap.values()));
}

private static String getSortedItem(String item) {
char[] charArr = item.toLowerCase().toCharArray();
char temp;
for (int i = 0; i < charArr.length; i++) {
for (int j = i + 1; j < charArr.length; j++) {
if (charArr[j] < charArr[i]) {
temp = charArr[j];
charArr[j] = charArr[i];
charArr[i] = temp;
}
}
}
return String.valueOf(charArr);
}
}