Skip to content

Instantly share code, notes, and snippets.

@gaoyike
Created June 15, 2014 16:20
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 gaoyike/2839135b288b36d984e8 to your computer and use it in GitHub Desktop.
Save gaoyike/2839135b288b36d984e8 to your computer and use it in GitHub Desktop.
1.3
/**
* Created by Readman on 6/16/14.
*/
public class permutationString {
/*
time: n
space : 1
* */
public static boolean perm (String s1, String s2) {
if (s1 == null || s2 == null)
return false;
if (s1.isEmpty() && s2.isEmpty())
return true; // two empty strings are permutation.
if (s1.isEmpty() || s2.isEmpty())
return false;
if (s1.length() != s2.length())
return false;
int[] test = new int[256];
for (char c : s1.toCharArray()) {
test[c] += 1;
}
for (char c : s2.toCharArray()) {
test[c] -= 1;
}
for (int i : test) {
if (i != 0)
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(perm("acc", "ccc"));
}
}
@jackson-rz
Copy link

line 22 to 28 can be changed into
for(char c : str2.toCharArray()) {
if (--letters[c] < 0) {
return false;
}
}

Is this better? :)

@XinboChen
Copy link

I think in 14, if should be change to if(s1.isEmpty()+ s2.isEmpty()==0);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment