242. Valid Anagram (验证异位字)

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

Example 1:spa

Input: s = "anagram", t = "nagaram"
Output: true
复制代码

Example 2:code

Input: s = "rat", t = "car"
Output: false
复制代码

这道题其实不难,做为easy的题目来讲,难度还ok。cdn

基本上无非就是用hashmap之类的进行计数,统计不一样字符的出现个数。blog

若是出现次数相同互为异位字。string

与此同理,若是连长度都不一样那直接false结束。hash

这边我采用了数组进行统计,也是相对而言比较简单的一种方式。it

代码以下:io

class Solution {
    private int[] S = new int[128];
    private int[] T = new int[128];
    
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;

        for (int i = 0, l = s.length(); i < l; i++) {
            S[s.charAt(i)]++;
        }

        for (int i = 0, l = t.length(); i < l; i++) {
            T[t.charAt(i)]++;
        }

        for (int i = 0; i < 128; i++) {
            if (S[i] != T[i]) return false;
        }

        return true;
    }
}
复制代码

利用ASCII的规则,其实每一个字母都有对应的数字好比A就是65,具体对应关系看下表: function

因此实际上咱们真正利用到的也就是65-122之间的字母,由于数组是经过index来获得对应的值。也就是说咱们利用数字来对应字母,value来标记其出现次数,这样就能验证对应的字母出现个数从而方便统计。

相关文章
相关标签/搜索