Coding

242. Valid Anagram

2023-12-16 1 min read

題目敘述

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1

Input: s = “anagram”, t = “nagaram” Output: true

Example 2

Input: s = “rat”, t = “car” Output: false

解題思路

Solution

import java.util.Arrays;

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) return false;

        char[] arrs = s.toCharArray();
        char[] arrt = t.toCharArray();

        Arrays.sort(arrs);
        Arrays.sort(arrt);

        for(int i = 0; i < arrs.length; i++){
            if(arrs[i] != arrt[i]) return false;
        }

        return true;
    }
}
← Posts
meow~