Created
May 1, 2021 22:03
-
-
Save gurbuzali/b25c62edc42e4ec42fc0683c6cae67b9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public class IsAnagram { | |
boolean anagram(String s1, String s2) { | |
if(s1.length() != s2.length()) { | |
return false; | |
} | |
int[] counts = new int[26]; | |
for(int i=0; i<s1.length(); i++) { | |
//'a' - 'a' -> 0, 'b' - 'a' -> 1 .... | |
counts[s1.charAt(i)-'a']++; | |
} | |
for(int i=0; i<s1.length(); i++) { | |
counts[s2.charAt(i)-'a']--; | |
if(counts[s2.charAt(i)-'a'] < 0)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
m = s1#length
n = s2#length
Time complexity O(m+n)
space complexity O(1), fixed size int[]