Add one more solution for anagrams check (#4175)
This commit is contained in:
parent
bb830e9559
commit
89b7ee42e6
@ -43,6 +43,8 @@ public class Anagrams {
|
|||||||
* Auxiliary Space Complexity : O(1)
|
* Auxiliary Space Complexity : O(1)
|
||||||
* 4th approach Time Complexity : O(n)
|
* 4th approach Time Complexity : O(n)
|
||||||
* Auxiliary Space Complexity : O(n)
|
* Auxiliary Space Complexity : O(n)
|
||||||
|
* 5th approach Time Complexity: O(n)
|
||||||
|
* Auxiliary Space Complexity: O(1)
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -122,4 +124,27 @@ public class Anagrams {
|
|||||||
return nm.equals(kk);
|
return nm.equals(kk);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
boolean approach5(String s, String t) {
|
||||||
|
if(s.length() != t.length()){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Approach is different from above 4 aproaches.
|
||||||
|
// Here we initialize an array of size 26 where each element corresponds to the frequency of a character.
|
||||||
|
int[] freq = new int[26];
|
||||||
|
// iterate through both strings, incrementing the frequency of each character in the first string and decrementing the frequency of each character in the second string.
|
||||||
|
for(int i=0; i<s.length(); i++){
|
||||||
|
int pos1 = s.charAt(i) - 'a';
|
||||||
|
int pos2 = s.charAt(i) - 'a';
|
||||||
|
freq[pos1]++;
|
||||||
|
freq[pos2]--;
|
||||||
|
}
|
||||||
|
// iterate through the frequency array and check if all the elements are zero, if so return true else false
|
||||||
|
for(int i=0; i<26; i++){
|
||||||
|
if(freq[i] != 0){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,5 +18,6 @@ public class AnagramsTest {
|
|||||||
assertTrue(anagrams.approach3(input1, "teal"));
|
assertTrue(anagrams.approach3(input1, "teal"));
|
||||||
assertTrue(anagrams.approach4(input1, "tale"));
|
assertTrue(anagrams.approach4(input1, "tale"));
|
||||||
assertTrue(anagrams.approach4(input1, "teal"));
|
assertTrue(anagrams.approach4(input1, "teal"));
|
||||||
|
assertTrue(anagrams.approach5(input1, "teal"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user