Created
February 7, 2014 05:17
-
-
Save Jeffwan/8857663 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. CC150 - Arrays and Strings.
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
| package CC150.ArraysAndString; | |
| /** | |
| * I misunderstand the defination of permutation. I treat it as reverse. | |
| * Permutation means anyway, but reversed. abb is a permutation of bab. | |
| * Permutation feature: the count of ever number is same, any combination is valid | |
| */ | |
| public class Permutation { | |
| public static void main(String[] args) { | |
| System.out.println(permutation("fabcdfedfaaa","abacdaedfaff")); | |
| } | |
| /** | |
| * Check if the two strings have identical character counts -- the permutation is not same as I think | |
| * | |
| * make ever char as position, and increase | |
| */ | |
| public static boolean permutation(String s, String t) { | |
| if (s.length() != t.length()) { | |
| return false; | |
| } | |
| int[] arr = new int[256]; // assume character is ASCII | |
| for (int i=0; i< s.length(); i++) { | |
| char value = s.charAt(i); | |
| arr[value] ++; | |
| } | |
| for (int i=0; i< t.length(); i++) { | |
| int value = t.charAt(i); | |
| if (--arr[value] < 0) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| /** | |
| * Sort two strings and compare(use sort api) | |
| */ | |
| public static boolean permutation2(String s, String t) { | |
| if (s.length() != t.length()) { | |
| return false; | |
| } | |
| return sort(s).equals(sort(t)); | |
| } | |
| public static String sort(String str) { | |
| char[] temp = str.toCharArray(); | |
| java.util.Arrays.sort(temp); | |
| return new String(temp); | |
| } | |
| /** | |
| * My Solution | |
| * s[0] == t[length-1] s[1] == t[length-1-1] .... | |
| * two pointer, one is on s header, the other one is on t end, make comparation | |
| */ | |
| public static boolean permutation3 (String s, String t) { | |
| if (s == null || t == null) { | |
| return false; | |
| } | |
| if (s.length() != t.length()) { | |
| return false; | |
| } | |
| for (int i= 0; i< s.length(); i++) { | |
| if (s.charAt(i) != t.charAt(s.length() -1 - i)) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm, I believe that your solution permutation3 is not quite right, since it is checking the first letter of s and last element of t. So, let's say: s = "dog" and t = "odg", which should return true, but when you run your solution, it will print out it is not permutation.