LeetCode题解:Valid Anagram

来源:互联网 发布:mac windows 共享文件 编辑:程序博客网 时间:2024/06/04 19:02

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.

题意是说,给定两个字符串s和t,判断t是否为由s的组成字符颠倒顺序构成的。

所以解决问题的思路很简单:

  1. 用HashMap创建s中出现的所有字母及其出现次数的映射表,依次比较t中字符及次数就可以得到结果

  2. 用一个长度为26的数组存储字母’a’-‘z’对应的出现次数,数组对应的值减去用t中字母的出现次数,只要数组中所有元素的值不为0,就代表匹配失效

其实两种思路本质是一样的:创建映射表,只不过空间开销和时间开销不一样。

代码:

1、

public boolean isAnagram(String s, String t) {    if(s == null && t == null) return true;    if(s == null || t == null) return false;    if(s.length() != s.length()) return false;    HashMap<Character, Integer> map = new HashMap<Character, Integer>();    for(int i = 0; i < s.length(); i++) {        if(map.containsKey(s.charAt(i))) {            int value = map.get(s.charAt(i));            map.put(s.charAt(i), ++value);        }        else {            map.put(s.charAt(i), 1);        }    }    for(int j = 0; j < t.length(); j++) {        if(map.containsKey(t.charAt(j))) {            int value = map.get(t.charAt(j));            if(--value == 0) {                map.remove(t.charAt(j));            }            else {                map.put(t.charAt(j), value);            }        }        else            return false;    }    if(map.isEmpty()) return true;    else return false;}

2、

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