Leetcode Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
解题思路:(两种方法)
1. 利用JAVA library 自带的Arrays.sort. That sort method uses the quicksort algorithm. 排序完后比较两个string, 相同则true, 不同则false. run time 一般。
2. 我们先判断两个字符串长度是否相同,不相同直接返回false。然后把s中所有的字符出现个数统计起来,存入一个大小为26的数组中,因为题目中限定了输入字符串为小写字母组成。然后我们再来统计t字符串,如果发现不匹配则返回false。 run time 很快。
Java code:
1 import java.util.Arrays; 2 3 public class ValidAnagram { 4 public static void main(String[] args) { 5 boolean x = isAnagram("anagram", "nagaram"); 6 System.out.println(x); 7 } 8 9 /* 10 * method1: use Arrays.sort 11 * run time Medium 12 * */ 13 public static boolean isAnagram(String s, String t) { 14 if(s.length() != t.length()) { return false; } 15 char[] s1 = s.toCharArray(); 16 Arrays.sort(s1); 17 String s_sorted = String.valueOf(s1); 18 char[] t1 = t.toCharArray(); 19 Arrays.sort(t1); 20 String t_sorted = String.valueOf(t1); 21 if(s_sorted.equals(t_sorted)) {return true;} 22 return false; 23 } 24 25 /* 26 * method2 27 * run time Fast! 28 * */ 29 public static boolean isAnagram(String s, String t) { 30 if(s.length() != t.length()) { return false; } 31 int[] m = new int[26]; 32 for(int i= 0; i< s.length(); i++) { 33 m[s.charAt(i)-'a']++; 34 } 35 for(int i= 0; i< t.length(); i++){ 36 m[t.charAt(i)-'a']--; 37 } 38 for(int i=0; i< 26; i++) { 39 if(m[i]!=0) {return false;} 40 } 41 return true; 42 } 43 }
Reference:
1. http://www.cnblogs.com/grandyang/p/4694988.html
2. http://bookshadow.com/weblog/2015/08/01/leetcode-valid-anagram/