Last active
August 29, 2015 14:02
-
-
Save chouclee/0fb6ccc84d604d50a14e to your computer and use it in GitHub Desktop.
[CC150][1.3] Given two strings, write a method to decide if one is a permutation of the other. (Consider case sensitivity and whitespace as significant)
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
import java.util.HashMap; | |
public class permutation { | |
public static boolean isPermut(String a, String b) { | |
if (a == null || b == null) throw new NullPointerException(); | |
if (a.length() != b.length()) return false; | |
HashMap<Character, Integer> aMap = new HashMap<Character, Integer>(); | |
HashMap<Character, Integer> bMap = new HashMap<Character, Integer>(); | |
traverse(a, aMap); | |
traverse(b, bMap); | |
if(aMap.keySet().size() != bMap.keySet().size()) return false; | |
for (Character key : aMap.keySet()) | |
if (!aMap.get(key).equals(bMap.get(key))) | |
return false; | |
return true; | |
} | |
private static void traverse(String s, HashMap<Character, Integer> map) { | |
Integer count; | |
for (int i = 0; i < s.length(); i++) { | |
count = map.get(s.charAt(i)); | |
if (count == null) | |
map.put(s.charAt(i), 1); | |
else map.put(s.charAt(i), count + 1); | |
} | |
} | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
String a, b; | |
a = "我为人人"; | |
b = "人人为我"; | |
System.out.println(permutation.isPermut(a, b) ? "Yes" : "No"); | |
a = "It's just a test right?"; | |
b = "It's just a right test?"; | |
System.out.println(permutation.isPermut(a, b) ? "Yes" : "No"); | |
a = ""; | |
b = " "; | |
System.out.println(permutation.isPermut(a, b) ? "Yes" : "No"); | |
a = "Abcdef"; | |
b = "fedcba"; | |
System.out.println(permutation.isPermut(a, b) ? "Yes" : "No"); | |
a = "ありがとう"; | |
b = "うありがと"; | |
System.out.println(permutation.isPermut(a, b) ? "Yes" : "No"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment