LeetCode#242: Valid Anagram

xiaoxiao2025-08-31  9

Description

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

Example

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.

Solution

此题要求判断一个字符串是否为另一个字符串的相同字母异序词。

当字符串中只包含二十六个英文字母时,可以创建一个长度为26的字符数组,遍历参数中的两个字符串,对于遍历第一个字符串中得的字符,在数组中将其加一,而对于遍历第二个字符串中得到的字符,在数组中将其减一。如此一来,如果一个字符串为另一个字符串的相同字母异序词,则二十六个英文字母所对应的下标下的值应该都为0,如果有不为0的值,则说明这两个字符串不是相同字母异序词。

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

进一步思考,当字符串中不仅包含二十六个英文字母,而也有可能包含其它字符的时候,用字符数组就不太合理了,因为这个字符数组将会很大。此时可以考虑用HashMap来求解:

public class Solution { public boolean isAnagram(String s, String t) { if(s.length() != t.length()) return false; HashMap<Character, Integer> map = new HashMap<>(); for(int i = 0; i < s.length(); i++) { map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0)+1); map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0)-1); } for(Map.Entry<Character, Integer> entry : map.entrySet()) { if(entry.getValue() != 0) return false; } return true; } }
转载请注明原文地址: https://www.6miu.com/read-5035505.html

最新回复(0)