728x90
반응형
242. Valid Anagram
LeetCode
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
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
두 문자열 s와 t가 주어졌을 때, t가 s의 애너그램(anagram)이면 true를, 아니면 false를 반환하세요.
Example
Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
1. 문제 요구사항 분석
단어가 같은지 확인
2. 접근 전략
😁 알파벳 배열 만들어서 첫 번째 배열의 알파벳을 +1 넣고, 두 번째 배열 알파벳을 -1 하면 모든 값이 0 이면 true, 그렇지 않으면 false
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
// 알파벳 배열
int[] alphabet = new int[26];
// s, t 알파벳 배열에 넣기
for (int i = 0; i < s.length(); i++) {
alphabet[s.charAt(i) - 'a']++;
alphabet[t.charAt(i) - 'a']--;
}
for (int a: alphabet) {
if (a != 0) return false;
}
return true;
}
}
🤩 정렬 후 비교 (Arrays 이용하기)
class Solution {
public boolean isAnagram(String s, String t) {
char[] arr1 = s.toCharArray();
char[] arr2 = t.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1,arr2);
}
}
728x90
반응형
'프로그래밍 > 알고리즘' 카테고리의 다른 글
| [LeetCode] 200. Number of Islands (0) | 2026.06.15 |
|---|---|
| [LeetCode] 226. Invert Binary Tree (0) | 2026.06.10 |
| [LeetCode] 190. Reverse Bits (0) | 2026.06.03 |
| [LeetCode] 56. Merge Intervals (0) | 2026.06.01 |
| [LeetCode] 268. Missing Number (0) | 2026.05.28 |