242. valid anagram java_Valid Anagram(leetcode242)

本文介绍了一种简单有效的方法来判断两个字符串是否为字母异位词,即两个字符串是否由相同的字符组成,只是顺序不同。通过两种方法实现:一种是使用数组计数字符出现次数;另一种是对字符串排序后进行直接比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

//如果是使用map 也是同样的效果 都是"桶"

public static boolean isAnagram(String s, String t) {

int[] alphabet = new int[26];

for (int i = 0; i < s.length(); i++) {

alphabet[s.charAt(i) - 'a']++;

}

for (int i = 0; i < t.length(); i++) {

alphabet[t.charAt(i) - 'a']--;

}

for (int i : alphabet) {

if (i != 0) {

return false;

}

}

return true;

}

//这是对字符数组 做了一个排序 然后比较

public static boolean isAnagram2(String s, String t) {

char[] sChar = s.toCharArray();

char[] tChar = t.toCharArray();

Arrays.sort(sChar);

Arrays.sort(tChar);

return Arrays.equals(sChar, tChar);

}

git:https://github.com/woshiyexinjie/leetcode-xin

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值