【Leetcode】242. Valid Anagram

来源:互联网 发布:广州企业名录数据库 编辑:程序博客网 时间:2024/06/06 09:16

方法一:

思路:

Hash表计数判相等。

public class Solution {    public boolean isAnagram(String s, String t) {        int lenS = s.length();        int lenT = t.length();        if (lenS != lenT)            return false;        Map<Character, Integer> map = new HashMap<Character, Integer>();        for (int i = 0; i < lenS; i++) {            if (map.containsKey(s.charAt(i)))                 map.put(s.charAt(i), map.get(s.charAt(i)) + 1);            else                map.put(s.charAt(i), 1);        }        for (int i = 0; i < lenT; i++) {            if (map.containsKey(t.charAt(i)) && map.get(t.charAt(i)) > 0)                 map.put(t.charAt(i), map.get(t.charAt(i)) - 1);            else                return false;        }        return true;    }}

Runtime:50ms


方法二:

思路:

转换为char[],不用Map,效率提升。

public class Solution {    public boolean isAnagram(String s, String t) {        int lenS = s.length();        int lenT = t.length();        if (lenS != lenT)            return false;        char[] ch1 = s.toCharArray();         char[] ch2 = t.toCharArray();         int[] temp = new int[128];        for (char ch : ch1)              temp[ch]++;         for (char ch : ch2) {             temp[ch]--;             if (temp[ch] < 0)                 return false;         }        return true;     }}
Runtime:3ms

1 0