|
| 1 | +package com.ctci.arraysandstrings; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * @author rampatra |
| 7 | + * @since 19/11/2018 |
| 8 | + */ |
| 9 | +public class CheckPermutation { |
| 10 | + |
| 11 | + private static boolean isOnePermutationOfOther(String s1, String s2) { |
| 12 | + if (s1.length() != s2.length()) { |
| 13 | + return false; |
| 14 | + } |
| 15 | + |
| 16 | + char[] c1 = s1.toCharArray(); |
| 17 | + char[] c2 = s2.toCharArray(); |
| 18 | + Arrays.sort(c1); |
| 19 | + Arrays.sort(c2); |
| 20 | + |
| 21 | + return Arrays.equals(c1, c2); |
| 22 | + } |
| 23 | + |
| 24 | + private static boolean isOnePermutationOfOtherGivenThatStringsContainOnlyAscii(String s1, String s2) { |
| 25 | + if (s1.length() != s2.length()) { |
| 26 | + return false; |
| 27 | + } |
| 28 | + |
| 29 | + int[] chars = new int[128]; // assuming strings contain only ASCII characters |
| 30 | + |
| 31 | + for (int i = 0; i < s1.length(); i++) { |
| 32 | + chars[s1.charAt(i)]++; |
| 33 | + } |
| 34 | + |
| 35 | + for (int i = 0; i < s2.length(); i++) { |
| 36 | + chars[s2.charAt(i)]--; |
| 37 | + if (chars[s2.charAt(i)] < 0) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + } |
| 41 | + return true; |
| 42 | + } |
| 43 | + |
| 44 | + public static void main(String[] args) { |
| 45 | + System.out.println(isOnePermutationOfOther("ram", "mar")); |
| 46 | + System.out.println(isOnePermutationOfOther("rama", "mar")); |
| 47 | + System.out.println(isOnePermutationOfOther("rama", "marA")); |
| 48 | + System.out.println("-------"); |
| 49 | + System.out.println(isOnePermutationOfOtherGivenThatStringsContainOnlyAscii("ram", "mar")); |
| 50 | + System.out.println(isOnePermutationOfOtherGivenThatStringsContainOnlyAscii("rama", "mar")); |
| 51 | + System.out.println(isOnePermutationOfOtherGivenThatStringsContainOnlyAscii("rama", "marA")); |
| 52 | + } |
| 53 | +} |
0 commit comments