엔지니어 게시판
LeetCode 솔루션 분류

[7/28] 242. Valid Anagram

컨텐츠 정보

본문

Easy
5889232Add to ListShare

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?

Accepted
1,473,092
Submissions
2,373,483

관련자료

댓글 4

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 73 ms, faster than 56.26% of Python3 online submissions for Valid Anagram.
Memory Usage: 14.4 MB, less than 96.92% of Python3 online submissions for Valid Anagram.
import collections
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return collections.Counter(s) == collections.Counter(t)

재민재민님의 댓글

  • 익명
  • 작성일
Runtime: 23 ms, faster than 22.74% of C++ online submissions for Valid Anagram.
Memory Usage: 7.4 MB, less than 46.64% of C++ online submissions for Valid Anagram.
public:
    bool isAnagram(string s, string t) {
        map<char, int> m;
        for(auto c : s)
            m[c]++;
        
        for(auto c : t)
        {
            if(m.find(c) == m.end())
                return false;
            m[c]--;
        }
        
        for(auto itr = m.begin(); itr != m.end(); itr++)
            if(itr->second != 0)
                return false;
        return true;
    }
};

재민재민님의 댓글

  • 익명
  • 작성일
Runtime: 16 ms, faster than 48.54% of C++ online submissions for Valid Anagram.
Memory Usage: 7.3 MB, less than 46.64% of C++ online submissions for Valid Anagram.
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end() );
        sort(t.begin(), t.end() );
        
        if(s.size() != t.size())
            return false;
        for(int i = 0; i < s.size(); i++)
            if(s[i] != t[i])
                return false;
        
        
        return true;
    }
};

재민재민님의 댓글

  • 익명
  • 작성일
Runtime: 12 ms, faster than 64.75% of C++ online submissions for Valid Anagram.
Memory Usage: 7.3 MB, less than 78.25% of C++ online submissions for Valid Anagram.
class Solution {
public:
    bool isAnagram(string s, string t) {
        vector<int> map(26,0);
        
        for(char c : s)
            map[c-'a']++;
        for(char c : t)
            map[c-'a']--;
        
        for(auto it = map.begin(); it != map.end(); it++)
            if(*it != 0)
                return false;
        
        return true;
    }
};
전체 396 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 156 명
  • 오늘 방문자 780 명
  • 어제 방문자 5,148 명
  • 최대 방문자 11,134 명
  • 전체 회원수 1,086 명
알림 0