242. Valid Anagram Java Solutin

本文提供了一个方法来判断两个字符串是否互为变位词,即它们包含相同的字符,只是排列顺序不同。通过使用一个大小为26的数组存储每个字母的出现次数,可以高效地进行比较。同时,文章还探讨了如何适应包含Unicode字符的情况。

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

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

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return 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?

 

Subscribe to see which companies asked this question

由题 只有小写字母,使用26位的数组存储每个字母个数进行比较。

 1 public class Solution {
 2     public boolean isAnagram(String s, String t) {
 3         if(s == null || t == null || s.length() != t.length())
 4             return false;
 5         int[] cmap = new int[26];
 6         for(int i=0;i<s.length();i++){
 7             cmap[s.charAt(i)-'a']++;
 8             cmap[t.charAt(i)-'a']--;
 9         }
10         for(int c : cmap){
11             if(c != 0)
12                 return false;
13         }
14         return true;
15     }
16 }

 

转载于:https://www.cnblogs.com/guoguolan/p/5383587.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值