242. Valid Anagram

来源:互联网 发布:淘宝天猫怎么抢红包 编辑:程序博客网 时间:2024/06/14 00:14

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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

这道题tag上有hashtable,第一反应用hashmap类,其实这是让用hashtable的思想,比如用int[26] 的数组存s中各个字母出现的次数,然后遍历t 中的各个字母减去对应的int[26]存的次数。代码如下:

public class Solution {    public boolean isAnagram(String s, String t) {        if (s.length() != t.length()) {            return false;        }        int[] charmap = new int[26];        for (int i = 0; i < s.length(); i++) {            charmap[s.charAt(i) - 'a'] ++;            charmap[t.charAt(i) - 'a'] --;        }        for (int count:charmap) {            if(count != 0) {                return false;            }        }        return true;    }}

0 0
原创粉丝点击