[LeetCode] 242. Valid Anagram

博客围绕LeetCode上判断两个字符串是否为相同字母异序词的题目展开。先介绍题目,给出示例并提出输入含Unicode码的拓展问题。接着给出两种解题思路,一是先排序后比较,二是记录出现过的字母及次数,还提及含Unicode字符时可用HashMap处理。

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

原题链接:https://leetcode.com/problems/valid-anagram/

1. 题目介绍

Given two strings s and t , write a function to determine if t is an anagram of s.
给出两个字符串 s 和 t,写一个函数判断它们两个是不是相同字母异序词。

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?
如果输入不仅仅是字母,还包括Unicode码怎么办?如何调整你的方法?

2. 解题思路

2.1 方法1 先排序,后比较

可以将字符串中的字符进行排序,然后再比较排序以后的字符串是否相等。具体步骤如下:

  1. 将字符串转成字符数组
  2. 对字符数组按照字典序进行排序
  3. 将排序好的字符数组转回字符串
  4. 比较两个新的字符串是否一样

具体实现代码如下:
实现代码

class Solution {
    public boolean isAnagram(String s, String t) {
        char [] a = s.toCharArray();
     	char [] b = t.toCharArray();

     	Arrays.sort(a);
		Arrays.sort(b);

		String news = new String(a);
		String newt = new String(b);

		return news.equals(newt);
    }
}

当然,也可以在第三步直接判断两个字符数组是否相等。
实现代码

class Solution {
    public boolean isAnagram(String s, String t) {
        char [] a = s.toCharArray();
     	char [] b = t.toCharArray();

     	Arrays.sort(a);
		Arrays.sort(b);

		return Arrays.equals(a, b);
    }
}

2.2 方法2 记录出现过的字母

注:本思路来自LeetCode上本题的Solution,有兴趣的读者可以去看原文:https://leetcode.com/problems/valid-anagram/solution/


首先遍历一遍字符串 s ,记录所有出现过的字母及次数。然后遍历一遍字符串 t ,如果出现了和字符串 s 中相同的字母,那么就将该字母次数减一。最后,如果所有的字母出现的次数都是0的话,说明 s 和 t 是相同字母异序词。

如果输入不仅仅是小写字母,还包括Unicode字符,那么就可以利用HashMap来记录出现过的字符及其次数。

class Solution {
    public boolean isAnagram(String s, String t) {
		if (s.length() != t.length()) {
			return false;
		}
		int [] a = new int [26];
        for (int i = 0; i< s.length() ; i++ ) {
        	a[s.charAt(i) - 'a'] ++;
        }

        for (int i = 0; i< t.length() ; i++ ) {
        	a[t.charAt(i) - 'a'] --;
        }
        for (int i = 0; i< a.length ; i++ ) {
        	if (a[i] != 0) {
        		return false;
        	}
        }
		return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值