diff --git a/Java/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionA.java b/Java/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionA.java index 22cb6e27..4c4f244b 100644 --- a/Java/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionA.java +++ b/Java/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionA.java @@ -1,16 +1,19 @@ package Q1_02_Check_Permutation; -public class QuestionA { +public class QuestionA { public static String sort(String s) { char[] content = s.toCharArray(); java.util.Arrays.sort(content); return new String(content); } - + public static boolean permutation(String s, String t) { + if (s.equals(t) || s.length() != t.length()) { // Permutations must have the same characters, but in different orders and must be same length + return false; + } return sort(s).equals(sort(t)); - } - + } + public static void main(String[] args) { String[][] pairs = {{"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}}; for (String[] pair : pairs) { diff --git a/Java/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionB.java b/Java/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionB.java index 762f82a0..1f69a954 100644 --- a/Java/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionB.java +++ b/Java/Ch 01. Arrays and Strings/Q1_02_Check_Permutation/QuestionB.java @@ -1,24 +1,26 @@ package Q1_02_Check_Permutation; -public class QuestionB { +public class QuestionB { public static boolean permutation(String s, String t) { - if (s.length() != t.length()) return false; // Permutations must be same length - + if (s.equals(t) || s.length() != t.length()) { // Permutations must have the same characters, but in different orders and must be same length + return false; + } + int[] letters = new int[128]; // Assumption: ASCII for (int i = 0; i < s.length(); i++) { letters[s.charAt(i)]++; } - + for (int i = 0; i < t.length(); i++) { letters[t.charAt(i)]--; if (letters[t.charAt(i)] < 0) { return false; } } - + return true; // letters array has no negative values, and therefore no positive values either } - + public static void main(String[] args) { String[][] pairs = {{"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}}; for (String[] pair : pairs) {