g0201_0300.s0242_valid_anagram.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0201_0300.s0242_valid_anagram;
// #Easy #Top_Interview_Questions #String #Hash_Table #Sorting #Data_Structure_I_Day_6_String
// #Programming_Skills_I_Day_11_Containers_and_Libraries #Udemy_Strings
// #2022_07_05_Time_2_ms_(99.01%)_Space_42.4_MB_(91.86%)
/**
* 242 - Valid Anagram\.
*
* Easy
*
* Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
*
* **Example 1:**
*
* **Input:** s = "anagram", t = "nagaram"
*
* **Output:** true
*
* **Example 2:**
*
* **Input:** s = "rat", t = "car"
*
* **Output:** false
*
* **Constraints:**
*
* * 1 <= s.length, t.length <= 5 * 104
* * `s` and `t` consist of lowercase English letters.
*
* **Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
**/
public class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] charFreqMap = new int[26];
for (char c : s.toCharArray()) {
charFreqMap[c - 'a']++;
}
for (char c : t.toCharArray()) {
if (charFreqMap[c - 'a'] == 0) {
return false;
}
charFreqMap[c - 'a']--;
}
return true;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy