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 * 104s 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?
두 문자열 s와 t가 주어지면 t가 s의 애너그램이면 참을 반환하고, 그렇지 않으면 거짓을 반환합니다.
애너그램은 다른 단어나 구의 글자를 재배열하여 만든 단어 또는 구문으로, 일반적으로 원래 글자를 모두 정확히 한 번 사용합니다.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Follow up: 입력에 유니코드 문자가 포함되어 있다면 어떻게 해야 할까요? 이러한 경우 솔루션을 어떻게 조정하시겠습니까?
class Solution {
public boolean isAnagram(String s, String t) {
char[] sChar = s.toCharArray();
char[] tChar = t.toCharArray();
for (int temp : sChar) {
sSum += temp;
}
for (int temp : tChar) {
tSum += temp;
}
return sSum == tSum;
}
}
문자열을 합쳐서 서로 같은 문자열이면 true를 반환하도록 해보았는데 문자열이 다르더라도 합계가 같아버리면 true로 나오기 때문에 테스트의 실패하였다. 예를 들면 "ac", "bb"는 97+99 == 98 +98로 같은 합계로 떨어져버린다.
문자열을 캐릭터 배열로 변환;
캐릭터 배열 정렬;
두개의 캐릭터 배열이 같은 배열이면 true 반환;
class Solution {
public boolean isAnagram(String s, String t) {
char[] sChar = s.toCharArray();
char[] tChar = t.toCharArray();
Arrays.sort(sChar);
Arrays.sort(tChar);
return Arrays.equals(sChar, tChar);
}
}