Valid Anagram from LeetCode

Given two strings s and t, write a function to determine if t is an anagram of s.java

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.数组

Note:
You may assume the string contains only lowercase alphabets.spa


题目比较直观,只须要检查两个字符串中,相同字符是否出现了一样的次数,而且没有多余的字符,便可;code

public class Solution {
    public boolean isAnagram(String s, String t) {
        int[] map = new int[26];

        char[] cs = s.toCharArray();

        for(char c : cs) {
            int x = c - 'a';
            map[x] += 1;
        }

        cs = t.toCharArray();

        for(char c : cs) {
            int x = c - 'a';
            if(map[x] == 0) {
                return false;
            }
            map[x] -= 1;
        }

        for(int x : map) {
            if(x != 0) {
                return false;
            }
        }
        return true;
    }
}
  1. 利用题目中只会出现小写字母,能够使用一个26位的int数组,分别表示a~z的出现的次数;orm

  2. 先计算s中字符出现的次数,字符串

  3. 而后遍历t,并减小该字符出现的次数;若是遇到某个字符,其出现次数已经被减到了0,那么该字符是在t中多出现了一次,返回false便可;string

  4. 遍历完t,再检查一遍是否有字符的出现次数没有被减到0的状况;若是存在,说明该字符在s中出现的次数比在t中多;返回false;it

  5. 最后返回true便可;io

  6. 时间复杂度为o(n), 空间复杂度为常量;
    function

相关文章
相关标签/搜索