Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LC242. 有效的字母异位词🤓🤓 #19

Open
HealUP opened this issue May 11, 2023 · 0 comments
Open

LC242. 有效的字母异位词🤓🤓 #19

HealUP opened this issue May 11, 2023 · 0 comments
Labels
算法 记录刷题记录,代码随想录

Comments

@HealUP
Copy link
Owner

HealUP commented May 11, 2023

哈希法—数组实现

思路分析

使用一个数组记录字符串S出现的次数,若该字母出现了一次,该位置的元素值加一;再遍历另外一个字符串,若出现一次就在数组对应位置的值减一。

因为字母是按顺序的,ASCII码上,每个字母也是相差1,随便取一个字母减去‘a’,就会得到该字母的下标了,然后在对应的record数组上,让该索引下的值+1

时间复杂度:O(n)

空间复杂度:O(1)

class Solution {
    public boolean isAnagram(String s, String t) {
        //哈希法 用数组来实现
        //定义一个统计字母出现次数的字符串
        int[] record = new int[26];//开辟26个空间即可

        for (int i = 0; i < s.length(); i++) {
            record[s.charAt(i) - 'a']++;//因为字母是按顺序的,ASCII码上,每个字母也是相差1,随便取一个字母减去‘a’,就会得到该字母的下标了,然后在对应的record数组上,让该索引下的值+1
        }
        for (int i = 0; i < t.length(); i++) {
            record[t.charAt(i) - 'a']--;
        }
        //只要record数组里面,不是0的,说明该位置的元素在两个字符串中不相等
        for (int count: record) {
            if (count != 0) {
                return false;
            }
        }
        return true;
    }
}
@HealUP HealUP added 算法 记录刷题记录,代码随想录 哈希法 labels May 11, 2023
@HealUP HealUP removed the 哈希法 label Jul 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 记录刷题记录,代码随想录
Projects
None yet
Development

No branches or pull requests

1 participant