Last active
August 29, 2015 14:16
-
-
Save EnesKorukcu/aadf52592d3a520078be to your computer and use it in GitHub Desktop.
Given two strings, write a method to decide if one is a permutation of the other.
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
/** | |
* Solution 1 | |
* @param str1 | |
* @param str2 | |
* @return boolean | |
*/ | |
public static boolean findIfStringsArePermutationOfEachOther(String str1, String str2) { | |
if(str1.length() != str2.length()) { | |
return false; | |
} | |
HashMap<Character, Integer> distinctChars1 = new HashMap<Character, Integer>(); | |
HashMap<Character, Integer> distinctChars2 = new HashMap<Character, Integer>(); | |
for(int i = 0; i < str1.length(); i++) { | |
Integer charCount1 = distinctChars1.get(str1.charAt(i)); | |
if(charCount1 == null) { | |
charCount1 = 0; | |
} | |
charCount1++; | |
distinctChars1.put(str1.charAt(i), charCount1); | |
Integer charCount2 = distinctChars2.get(str2.charAt(i)); | |
if(charCount2 == null) { | |
charCount2 = 0; | |
} | |
charCount2++; | |
distinctChars2.put(str2.charAt(i), charCount2); | |
} | |
for(Map.Entry<Character, Integer> entry : distinctChars1.entrySet()) { | |
if(!distinctChars2.get(entry.getKey()).equals(entry.getValue())) { | |
return false; | |
} | |
} | |
return true; | |
} | |
/** | |
* Solution 2 | |
* @param s | |
* @param t | |
* @return boolean | |
*/ | |
public static boolean permutation(String s, String t) { | |
if (s.length() != t.length()) { | |
return false; | |
} | |
// If all chars of string are ascii | |
int[] letters = new int[256]; | |
char[] s_array = s.toCharArray(); | |
for (char c : s_array) { | |
letters[c]++; | |
} | |
for (int i = 0; i < t.length(); i++) { | |
int c = (int) t.charAt(i); | |
if (--letters[c] < 0) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment