• leetcode 242. Valid Anagram(有效的字母异位词)


    Given two strings s and t, return true if t is an anagram of s, and false otherwise.

    An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

    Example 1:

    Input: s = “anagram”, t = “nagaram”
    Output: true
    Example 2:

    Input: s = “rat”, t = “car”
    Output: false

    给字符串s, t, 判断t 是不是s 的异位词。
    也就是判断t 的字母是不是 s中字母的重新排列,每个字母只用一次。

    思路
    t 是 s 中字母的重新排列,且每个字母只用一次;就意味着 t 只能用s中的字母,且只能用一次,
    那么s和t 的长度一定是相等的,不等的话肯定是false。

    不管怎么排列,首先要保证s 和 t 中的每个字母个数得是一致的,个数不一致的话s怎么排列都不会变成 t。
    那么只需要统计每个字母出现的个数,然后判断每个字母的个数是否一致即可。

    至于具体 s 怎么排列才能得到 t ,本题不关心。

    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) return false;
        
        int[] sc = new int[26];
        int[] tc = new int[26];
        
        for(int i = 0; i < s.length(); i++) {
            sc[s.charAt(i) - 'a'] ++;
            tc[t.charAt(i) - 'a'] ++;
        }
        
        for(int i = 0; i < 26; i++) {
            if(sc[i] != tc[i]) return false;
        }
        return true;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • 相关阅读:
    策略分享|复现经典K线形态:出水芙蓉
    Vue中Slot的使用指南
    关闭mysql,关闭redis服务
    凉鞋的 Godot 笔记 105. 第一个通识:编辑-测试 循环
    如何做好项目经理,你需要知道这些
    Android 获取某月所有的日期和星期
    C和C++区别联系
    前端——重要 发送表单数据 post
    JavaWeb后端学习
    LeetCode:771.宝石与石头
  • 原文地址:https://blog.csdn.net/level_code/article/details/126027501