(java)leetcode Valid Anagram

本文介绍了一种通过排序并比较两个字符串来判断它们是否互为字母异位词的方法。该方法首先检查两字符串长度是否相等,然后分别对两字符串的字符进行排序,最后比较排序后的字符串是否相同。

摘要生成于 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

思路:就是将两个字符串按照字符大小进行排序,然后比较两个拍好的字符串是否相等

代码如下(已通过leetcode)

public class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
String[] ss = new String[s.length()];
String[] tt = new String[t.length()];
for (int i = 0; i < s.length(); i++) {
ss[i] = "" + s.charAt(i);
tt[i] = "" + t.charAt(i);
}
Arrays.sort(ss);
Arrays.sort(tt);
boolean flag = true;
for (int i = 0; i < ss.length; i++) {
if (!ss[i].equals(tt[i])) {
flag = false;
}
}


return flag;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值