-
-
Save n2iw/c1e56af0ef1bd17f4522 to your computer and use it in GitHub Desktop.
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
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* | |
* @author james | |
* 1.3 Given two strings, write a method to decide if one is a permutation of the other. | |
* O(N) time, O(1) space | |
*/ | |
public class PermutationOfString { | |
public static boolean solution(String s1, String s2) { | |
if(s1 == null || s2 == null) { | |
return false; | |
} | |
if (s1.length() != s2.length()) { | |
return false; | |
} | |
Map<Character, Integer> counter = new HashMap<>(); | |
//using first string to populate counter table | |
for (int i = 0; i < s1.length(); ++i) { | |
char c = s1.charAt(i); | |
if (counter.containsKey(c)) { | |
counter.put(c, counter.get(c) + 1); | |
} else { | |
counter.put(c, 1); | |
} | |
} | |
//decrease counter for every character | |
for (int i = 0; i < s2.length(); ++i) { | |
char c = s2.charAt(i); | |
if (!counter.containsKey(c) || counter.get(c) <= 0) { | |
return false; | |
} | |
counter.put(c, counter.get(c) -1); | |
} | |
return true; | |
} | |
} |
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
import static org.junit.Assert.*; | |
import org.junit.Test; | |
public class PermutationOfStringTest { | |
@Test | |
public void test() { | |
assertEquals(PermutationOfString.solution(null, ""), false); | |
assertEquals(PermutationOfString.solution("", null), false); | |
assertEquals(PermutationOfString.solution(null, null), false); | |
assertEquals(PermutationOfString.solution("", ""), true); | |
assertEquals(PermutationOfString.solution("a", ""), false); | |
assertEquals(PermutationOfString.solution("", "a"), false); | |
assertEquals(PermutationOfString.solution("adeba", "bade"), false); | |
assertEquals(PermutationOfString.solution("adeba", "badea"), true); | |
assertEquals(PermutationOfString.solution("aabde", "edbaa"), true); | |
assertEquals(PermutationOfString.solution("aabde", "edbca"), false); | |
assertEquals(PermutationOfString.solution("aabde", "edbba"), false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment