II Hash Table: Valid Anagram

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;
    }
}

猜你喜欢

转载自blog.csdn.net/BaibuT/article/details/50449936