[Algorithm] Leetcode_ Valid Anagram

JAsmine_log·2024년 5월 6일
0

Valid Anagram

Problem

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

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?

Soultion & Analysis

count위한 임시 memory인 ascii배열을 만든다
String s를 처음부터 읽고, String t와 각 문자가 출현한 수 ++, --해주면서 비교한다
만약, 0이 출현했는데도 --하라고 하는 것은 이미 갯수가 맞지 않는것이다.
문자 길이가 다를수도 있는 경우도 있을 거 같아서 if조건 추가해보았다.

Code

# https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/882/

class Solution {
    public boolean isAnagram(String s, String t) {
        
        int[] ascii = new int[26];

        if (s.length() != t.length())
            return false;

        for (int i = 0; i < s.length(); i++)
            ascii[s.charAt(i) - 'a']++;

        for (int i = 0; i < t.length(); i++) {

            if (ascii[t.charAt(i) - 'a'] == 0)
                return false;

            ascii[t.charAt(i) - 'a']--;
        }
        return true;
    }
}
profile
Everyday Research & Development

0개의 댓글