Wednesday, June 19, 2013

cc150_1.3

Given two strings, write a method to decide if one is a permutation of the other.

//method 1: sort and compare
String sort(String s){
  char[] content = s.toCharArray();
  java.util.Arrays.sort(content);
  return new String(content);
}

public boolean permutation(String s, String t){
  if(s.length() != t.length()) return false;
  return sort(s).equals(sort(t));
}

//method 2: hash and compare
public boolean permutation(String s, String t) {
  if (s.length() != t.lengthQ)  return false;
  int[] count = new int[256];
  for(int i = 0; i < s.length(); i++){
     int ch = s.charAt(i);
     count[ch]++;
  }
 for(int i = 0; i < s.length(); i++){
     count[ch]--;
    if(count[ch] < 0) return false;
  }

  return true;

}

No comments:

Post a Comment