[leetcode #242] Valid Anagram

Seongyeol Shin·2022년 7월 28일
0

leetcode

목록 보기
195/196
post-thumbnail

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 * 10⁴
· 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?

Idea

주어진 두 문자열이 anagram인지 확인하는 문제다.

문자열을 구성하는 문자가 소문자로 한정되어 있으므로 알파벳 소문자의 개수로 배열을 구성한 뒤 문자열 s를 구성하는 문자의 수를 세어 저장한다. 이후 문자열 t를 구성하는 문자에 대해서는 count 값을 1씩 빼며, count 값이 음수일 때 false를 리턴한다.

문자열 t를 전부 탐색하고 루프를 빠져나왔을 경우 t가 s의 anagram이므로 true를 리턴한다.

Solution

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

        int[] cnt = new int[26];

        for (int i=0; i < s.length(); i++) {
            cnt['z' - s.charAt(i)]++;
        }
        for (int j=0; j < t.length(); j++) {
            int val = --cnt['z' - t.charAt(j)];
            if (val < 0) {
                return false;
            }
        }

        return true;
    }
}

Reference

https://leetcode.com/problems/valid-anagram/

profile
서버개발자 토모입니다

0개의 댓글