Skip to content

Instantly share code, notes, and snippets.

@Jocelyn9
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jocelyn9/d288fd5e38e7313ebb65 to your computer and use it in GitHub Desktop.
Save Jocelyn9/d288fd5e38e7313ebb65 to your computer and use it in GitHub Desktop.
1.3 Given two strings, write a method to decide if one is a permutation of the other.
/* Time complexity O(nlogn), Space complexity O(1) */
class Solution1{
boolean isPerm(String s1, String s2){
if(s1==null||s2==null) return false;
if(s1.length()!=s2.length()) return false;
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
for(int i=0; i<=s1.length()-1; i++){
if(arr1[i]!=arr2[i])
return false;
}
return true;
} //
} // end sol1
/*Time complexity: O(n), Space complexity: O(n)*/
class Solution2{
boolean isPerm(String s1, String s2){
if(s1==null||s2==null) return false;
if(s1.length()!=s2.length()) return false;
int[] temp = new int[256];
for(int i=0; i<=s1.length()-1; i++){
char c = s1.charAt(i);
temp[c]++;
}
for(int j=0; j<=s2.length()-1; j++){
char c2 = s2.charAt(j);
temp[c2]--;
if(temp[c2]<0){
return false;
}
}
return true;
}
} // end sol2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment