(Leetcode) [String] Valid anagram

Topic: String
Difficulty: Easy


Question

Given two strings s and t, return true if t is an anagram of s, and false otherwise.
anagram: a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.


Solution

10๋ถ„๋„ ์•ˆ ๊ฑธ๋ ค์„œ ํ’€์—ˆ๋‹ค. ์ด๋Ÿฐ ๋‚ ์ด ์˜ค๋‹ค๋‹ˆ.

Anagram์ด๋ž€ ์•ŒํŒŒ๋ฒณ์˜ ์ข…๋ฅ˜์™€ ๊ฐฏ์ˆ˜๋Š” ๋˜‘๊ฐ™์ง€๋งŒ ์ˆœ์„œ๊ฐ€ ์„œ๋กœ ๋‹ค๋ฅธ ๋‹จ์–ด๋ฅผ ๋œปํ•˜๋Š” ๋‹จ์–ด์ด๋‹ค. ๋‘ ๊ฐœ์˜ ๋ฌธ์ž์—ด์ด anagram์ธ์ง€ ํ™•์ธํ•˜๋ ค๋ฉด ๋ชจ๋“  ์•ŒํŒŒ๋ฒณ์˜ ์ข…๋ฅ˜๊ฐ€ ๊ฒน์น˜๋Š”์ง€, ๋˜ ๊ฐ ์•ŒํŒŒ๋ฒณ์˜ ๊ฐฏ์ˆ˜๊ฐ€ ๊ฐ™์€์ง€๋ฅผ ํ™•์ธํ•˜๋ฉด ๋œ๋‹ค.

  1. ์ผ๋‹จ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋ฉด ์ ˆ๋Œ€ anagram์ด ๋  ์ˆ˜ ์—†์œผ๋ฏ€๋กœ ์ฒซ๋ฒˆ์งธ ์ค„์—์„œ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ํ™•์ธํ•ด์คฌ๋‹ค.
  2. ํฌ๊ธฐ๊ฐ€ 26์ธ ๋‘ ๊ฐœ์˜ ๋ฐฐ์—ด์„ ํ˜•์„ฑํ•ด์„œ ๊ฐ ์•ŒํŒŒ๋ฒณ์˜ ๊ฐฏ์ˆ˜๋ฅผ ํ‘œ์‹œํ–ˆ๋‹ค. ๋ฌธ์ž์—ด์—์„œ ๊ฐ ์•ŒํŒŒ๋ฒณ์— a๋ฅผ ๋นผ์คŒ์œผ๋กœ์จ a์˜ index=0, b์˜ index=1, โ€ฆ , z์˜ index=26์ด ๋œ๋‹ค.
  3. ๋ฃจํ”„๋ฅผ ๋Œ๋ ค์„œ ๋‘ ๋ฐฐ์—ด์˜ element๊ฐ€ ๋ชจ๋‘ ๊ฐ™์€์ง€ ํ™•์ธํ•˜์—ฌ ์™„์ „ํžˆ ๊ฐ™์œผ๋ฉด true, ์•„๋‹ˆ๋ฉด false๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.
bool isAnagram(string s, string t) {
    if (s.length() != t.length())
        return false;

    int arr1[26] = { };
    int arr2[26] = { };

    for (int i=0; i<s.length(); i++) {
        arr1[s[i]-'a']++;
        arr2[t[i]-'a']++;
    }

    for (int j=0; j<26; j++) {
        if (arr1[j] != arr2[j])
            return false;
    }

    return true;
}


์˜ค๋Š˜์€ ๋ ˆํผ๋Ÿฐ์Šค ์—†์Œ~!

Categories:

Updated:

Leave a comment