Leetcode in Java && Oracle
422 subscribers
8 photos
397 files
400 links
Second channel: @codeforces_java

Let's Develop Together!
Download Telegram
image_2022-08-26_01-59-13.png
72.5 KB
#medium
#N49. Group Anagrams
problem link
#solution
public List<List<String>> groupAnagrams(String[] strs) {
Set<String> set=new HashSet<>();
List<List<String>> res=new ArrayList<>();
for(int i=0; i<strs.length; i++){
if(!set.contains(strs[i])){
set.add(strs[i]);
List<String> temp = new ArrayList<>();
temp.add(strs[i]);
for(int j=i+1; j<strs.length; j++){
if(isAnagram(strs[i], strs[j]) || strs[i].equals(strs[j])){
temp.add(strs[j]);
set.add(strs[j]);}}
res.add(temp);
}}return res;}
public boolean isAnagram(String s, String t) {
if (s.length()!=t.length()) return false;
int[] store=new int[26];
for (int i=0; i<s.length(); i++) {
store[s.charAt(i)-'a']++;
store[t.charAt(i)-'a']--;
}
for (int n : store) if (n!=0) return false;
return true;
}
👍3