Valid Anagram

2024. 10. 10. 14:22알고리즘/Leetcode

반응형

Solution

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

 

Examples

 

Constraints:

- 1 <= s.length, t.length <= 5 * 104

- s and t consist of lowercase English letters.

 

Explanation

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

        Arrays.sort(sArr);
        Arrays.sort(tArr);

        return Arrays.equals(sArr, tArr);
    }
}
 
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typicallyusing all the original letters exactly once. Therefore, we simply sort both strings and compare them.
 
First, to compare the strings s and t, they need to be converted to character arrays. Then, these arrays are sorted using the sorted() method.
 
Finally, the sorted arrays are compared, and the result is returned.
반응형

'알고리즘 > Leetcode' 카테고리의 다른 글

Implement strStr()  (0) 2024.10.14
Valid Palindrome  (2) 2024.10.11
First Unique Character in a String  (2) 2024.10.08
Reverse Integer  (0) 2024.10.07
Reverse String  (0) 2024.10.06