Algolithm-Leetcode/Arrays & Hashing
Valid Anagram
꿀잠마스터
2026. 8. 7. 19:43
https://leetcode.com/problems/valid-anagram/description/
Valid Anagram - LeetCode
Can you solve this real interview question? Valid Anagram - Given two strings s and t, return true if t is an anagram of s, and false otherwise. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: f
leetcode.com
두 문자열이 주어지고 하나의 문자열을 이루는 문자의 순서를 바꾸어 재구성 할 수 있는지 묻는 문제였다. 재구성 할 수 있다는 것은 동일한 개수의 문자를 가지고 있는 것이다.
따라서 알파벳 각각이 몇 개 있는지 확인하였다.
확인하기 위해서 알파벳 개수 크기의 배열을 두 개 만든 후 각각의 문자에 따라 배열의 인덱스의 값을 올려주었다. 그리고 두 배열의 값들을 비교하면 결과를 확인할 수 있다.
public class Solution {
public boolean isAnagram(String s, String t) {
// 글자의 길이가 다르다면 다른 것, for 문의 s.length()로 두 문자열의 문자를 순회할 것이므로 체크
if(s.length() != t.length()) return false;
int[] word1 = new int[26];
int[] word2 = new int[26];
for(int i = 0; i < s.length(); i++){
// 문자에 따라 인덱스의 값 증가, 'a'의 값 0번 인덱스로 하여 기준으로 한다.
word1[s.charAt(i) - 'a']++;
word2[t.charAt(i) - 'a']++;
}
for(int i = 0; i < word1.length; i++){
// 문자의 조합이 똑같은지 확인
if(word1[i] != word2[i]) return false;
}
return true;
}
}