Description
두개의 문자열이 주어졌을때 t가 s의 아나그램(철자를 바꿔서 구성한 단어)인지 여부를 반환하는 문제입니다.
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?
Solution 1. Hash Table
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length())return false;
int[] map = new int[26];
for (int i = 0; i < s.length(); i++) {
map[s.charAt(i)-'a']++;
}
for (int i = 0; i < t.length(); i++) {
if(--map[t.charAt(i)-'a'] < 0){
return false;
}
}
return true;
}
영어 소문자 26개의 크기를 가지는 배열을 HashTable로 사용하여 기준문자열(s)에서 각 알파벳 별 카운트를 기록해 놓은 뒤 동일한 길이가 사용되는지 count를 제외해 가며 체크합니다.
Reference
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 83. Remove Duplicates from Sorted List - 문제풀이 (0) | 2022.01.26 |
---|---|
[LeetCode] 203. Remove Linked List Elements - 문제풀이 (0) | 2022.01.25 |
[LeetCode] 941. Valid Mountain Array - 문제풀이 (0) | 2022.01.25 |
[LeetCode] 520. Detect Capital - 문제풀이 (0) | 2022.01.25 |
[LeetCode] 383. Ransom Note - 문제풀이 (0) | 2022.01.24 |