Created
July 17, 2020 03:27
-
-
Save gabrielagrandat/b657fd15d2fc0c844d34bbbfc9aea075 to your computer and use it in GitHub Desktop.
FunAnagrams - Hackerrank
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package practice; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.HashMap; | |
import java.util.List; | |
/** | |
* | |
* @author Gabriela Granda T | |
*/ | |
public class funAnagrams { | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
// TODO code application logic here | |
List<String> list = new ArrayList<>(); | |
list.add("code"); | |
list.add("doce"); | |
list.add("ecod"); | |
list.add("framer"); | |
list.add("frame"); | |
test(list); | |
} | |
public static void test(List<String> l) { | |
Object[] list = l.toArray(); | |
List<String> listReturn = new ArrayList<>(); | |
for (int i = 0; i < list.length; i++) { | |
for (int j = i + 1; j < list.length; j++) { | |
if (isAnagram(list[i].toString(), list[j].toString())) { | |
list[j] = ""; | |
} | |
} | |
listReturn.add(list[i].toString()); | |
Collections.sort(listReturn); | |
} | |
print(listReturn); | |
} | |
public static boolean isAnagram(String a, String b) { | |
boolean flag = false; | |
a = a.toLowerCase().trim(); | |
b = b.toLowerCase().trim(); | |
if (a.length() != b.length()) { | |
flag = false; | |
} else { | |
char[] newA = a.toCharArray(); | |
char[] newB = b.toCharArray(); | |
HashMap<Character, Integer> map = new HashMap<>(); | |
for (char letter : newA) { | |
if (map.get(letter) != null) { | |
int count = map.get(letter) + 1; | |
map.put(letter, count); | |
} else { | |
map.put(letter, 1); | |
} | |
} | |
for (char letterB : newB) { | |
if (map.get(letterB) != null) { | |
int count = map.get(letterB) - 1; | |
if (count == 0) { | |
map.remove(letterB); | |
} else { | |
map.put(letterB, count); | |
} | |
} else { | |
flag = false; | |
break; | |
} | |
} | |
flag = map.isEmpty(); | |
} | |
return flag; | |
} | |
public static void print(List<String> list) { | |
for (String l : list) { | |
System.out.print(l + " "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment