Skip to content
Open
Show file tree
Hide file tree
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
19 changes: 19 additions & 0 deletions Exercise1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution {
//I use a HahMap where the key is stored in sorted version of each string and the value is list of anagrams.
//Since anagrams share identical sorted character sequences, sorting normalizes them into the same key.
//I group all original strings under their sorted key and return all grouped values
public List<List<String>> groupAnagrams(String[] strs) {
HashMap <String, List<String>> map = new HashMap<>();
for(String str : strs){
char[] sortedArr = str.toCharArray();
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());
}
}

23 changes: 23 additions & 0 deletions Exercise2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
// I use two hashmaps to maintain one-to-one mapping between characters s and t
//for each index, i chek whether an existing mapping conflicts in either direction,if it does, return false
//If I finish loop without conflicts, the string are isomorphic, return true

public boolean isIsomorphic(String s, String t) {
HashMap<Character, Character> STmap = new HashMap<>();
HashMap<Character, Character> TSmap = new HashMap<>();
for(int i = 0; i < s.length(); i++){
char c1 = s.charAt(i);
char c2 = t.charAt(i);
if(STmap.containsKey(c1) && STmap.get(c1) != c2)
return false;
if(TSmap.containsKey(c2) && TSmap.get(c2) != c1)
return false;
STmap.put(c1, c2);
TSmap.put(c2,c1);

}
return true;

}
}
29 changes: 29 additions & 0 deletions Exercise3.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
// I split the string into words and checked if the pattern length matches the number of words.
// I used two hashmaps to maintain a bijetion - one mapaping pattern to words, other words to characters.
// while iterating, I return false if any existing mapping mismatchedl otherwise stored the mapping return true at the end.

public boolean wordPattern(String pattern, String s) {
String[]words = s.split(" ");
if(pattern.length() != words.length){
return false;
}
HashMap<Character, String> mapPT = new HashMap<>();
HashMap<String, Character>mapTP = new HashMap<>();
for (int i = 0; i < pattern.length(); i++){
char ch = pattern.charAt(i);
String word = words[i];
if(mapPT.containsKey(ch) && !mapPT.get(ch).equals(word)){
return false;

}
if(mapTP.containsKey(word)&&!mapTP.get(word).equals(ch)) {
return false;
}
mapPT.put(ch, word);
mapTP.put(word,ch);
}
return true;

}
}