1. Valid Anagram
given: two strings s and t, write a function to determine if t is an anagram of s.
e.g.
s="anagram", t="nagaram", return true.
s="rat", t="car", return false.
strategy: using java.util.Arrays.sort() method to sort the chars in the Strings
then compare two new sorted strings to see if they are equal. if it is
return true, otherwise return false.
public class Solution {
public boolean isAnagram(String s, String t) {
String x = sort(s);
String y = sort(t);
return (x.equals(y));
}
private static String sort(String a){
String original = a;
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
return sorted;
}
}
given: two strings s and t, write a function to determine if t is an anagram of s.
e.g.
s="anagram", t="nagaram", return true.
s="rat", t="car", return false.
strategy: using java.util.Arrays.sort() method to sort the chars in the Strings
then compare two new sorted strings to see if they are equal. if it is
return true, otherwise return false.
public class Solution {
public boolean isAnagram(String s, String t) {
String x = sort(s);
String y = sort(t);
return (x.equals(y));
}
private static String sort(String a){
String original = a;
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
return sorted;
}
}