diff --git a/GroupingAnagrams.java b/GroupingAnagrams.java new file mode 100644 index 00000000..a003895d --- /dev/null +++ b/GroupingAnagrams.java @@ -0,0 +1,23 @@ +import java.math.BigInteger; +// time complexity is O(N k log k ) +class Solution { + public List> groupAnagrams(String[] strs) { + // this is to check id we have already looked at a string with the same char + HashMap> map = new HashMap<>(); + + for (String str : strs) { + char[] sortedArr = str.toCharArray(); + // sorting will produce the same for each anagram + Arrays.sort(sortedArr); + String sortedStr = String.valueOf(sortedArr); + + if (!map.containsKey(sortedStr)) { + map.put(sortedStr, new ArrayList<>()); + } + + map.get(sortedStr).add(str); + } + + return new ArrayList<>(map.values()); + } +} \ No newline at end of file diff --git a/Isomorphic.java b/Isomorphic.java new file mode 100644 index 00000000..5aa0e2e1 --- /dev/null +++ b/Isomorphic.java @@ -0,0 +1,19 @@ +public class Isomorphic { + public boolean isIsomorphic(String s, String t) { + // to check the reverse order we need to store the reverse + char[] isormofic = new char[95]; + char[] reverseIsormofic = new char[95]; + // O (N) + for (int i = 0; i < s.length(); i++) { + if (isormofic[s.charAt(i) - ' '] != 0) { + if (reverseIsormofic[t.charAt(i) - ' '] != s.charAt(i)) return false; + } else { + // if reverse dont match then return false + if (reverseIsormofic[t.charAt(i) - ' '] != 0) return false; + reverseIsormofic[t.charAt(i) - ' '] = s.charAt(i); + isormofic[s.charAt(i) - ' '] = t.charAt(i); + } + } + return true; + } +} \ No newline at end of file diff --git a/WordPattern.java b/WordPattern.java new file mode 100644 index 00000000..873fb113 --- /dev/null +++ b/WordPattern.java @@ -0,0 +1,33 @@ +public class WordPattern { + public boolean wordPattern(String pattern, String s) { + Map charToWord = new HashMap<>(); + Map wordToChar = new HashMap<>(); + + char[] p = pattern.toCharArray(); + String[] words = s.split(" "); + // check if the length is the same + if (p.length != words.length) { + return false; + } + + for (int i = 0; i < p.length; i++) { + char c = p[i]; + String word = words[i]; + + if (charToWord.containsKey(c)) { + if (!charToWord.get(c).equals(word)) { + return false; + } + } else { + if (wordToChar.containsKey(word)) { + return false; + } + // if the sord doesnt already exist add them to the map and reverse map + charToWord.put(c, word); + wordToChar.put(word, c); + } + } + + return true; + } +} \ No newline at end of file