【LeetCode】242. Valid Anagram 有效的字母异位词(Easy)(JAVA)每日一题

【LeetCode】242. Valid Anagram 有效的字母异位词(Easy)(JAVA)

题目地址: https://leetcode.com/problems/valid-anagram/

题目描述:

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

Example 1:

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

Example 2:

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

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

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

题目大意

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

解题方法

  1. 因为字符串只包含小写字母,只要把所有的字母出现次数用一个数组存起来即可
  2. 一个字母的出现此处加起来,一个字母的出现次数减去,最终结果所有字母出现次数为 0 就是字母异位词
class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        int[] cou = new int[26];
        for (int i = 0; i < s.length(); i++) {
            cou[s.charAt(i) - 'a']++;
            cou[t.charAt(i) - 'a']--;
        }
        for (int i = 0; i < cou.length; i++) {
            if (cou[i] != 0) return false;
        }
        return true;
    }
}

执行用时:5 ms, 在所有 Java 提交中击败了 48.42% 的用户
内存消耗:38.6 MB, 在所有 Java 提交中击败了 86.53% 的用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值