【LeeCode】242. Valid anagrams

Given two strings*s* and *t*, write a function to determine whether *t* is*s* allophones.

Note:If the number of occurrences of each character in *s* and *t* is the same, it is called are anagrams of each other. *s* and *t*

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

The array is actually a simple hash table, and the string in this question only has lowercase characters, so you can define an array to record the occurrence of characters in the string s frequency.

How big an array needs to be defined? Just set an array called record with a size of 26 and initialize it to 0, because the ASCII characters a to z are also 26 consecutive values.

For the sake of convenience, let’s judge the string s= "aee", t = "eae".

Define an array called record to record the number of occurrences of characters in string s.

Characters need to be mapped to the array, that is, the index subscript of the hash table.Because the ASCII from character a to character z is 26 consecutive values, character a is mapped is subscript 0, and the corresponding character z is mapped to subscript 25.

When traversing the string s again, only needs to +1 the element where s[i] - 'a' is located, and there is no need to remember the character a ASCII, just ask for a relative value. In this way, the number of occurrences of characters in string s is counted.

Let’s take a look at how to check whether these characters appear in string t. Similarly, when traversing string t, perform a -1 operation on the value on the hash table index of the character mapping hash table that appears in t.

Then check finally,If some elements of the record array are not zero, it means that the strings s and t must have more characters or less characters, return false .

Finally, if all elements of the record array are zero, it means that the strings s and t are letter anagrams, and return true.

The time complexity is O(n). In terms of space, because the definition is an auxiliary array of constant size, the space complexity is O(1).

untie:

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

        for (int i = 0; i < s.length(); i++) {
            record[s.charAt(i) - 'a']++;     // 并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
        }

        for (int i = 0; i < t.length(); i++) {
            record[t.charAt(i) - 'a']--;
        }
        
        for (int count: record) {
            if (count != 0) {               // record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
                return false;
            }
        }
        return true;                        // record数组所有元素都为零0,说明字符串s和t是字母异位词
    }
}

Guess you like

Origin blog.csdn.net/weixin_48144018/article/details/134794323