반응형
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.
풀이(kotlin)
- 소문자 개수만큼의 배열을 만든 후 String s와 t 각각 character의 개수를 만큼 구하여 두 배열을 비교하였다.
class Solution {
fun isAnagram(s: String, t: String): Boolean {
if (s.length != t.length) return false
val lowerCaseSize = 'z' - 'a' + 1
val a = IntArray(lowerCaseSize)
val b = IntArray(lowerCaseSize)
for (i in s) a[i - 'a'] += 1
for (i in t) b[i - 'a'] += 1
for (i in a.indices) {
if (a[i] != b[i]) {
return false
}
}
return true
}
}
반응형
'Computer > Algorithm' 카테고리의 다른 글
LeetCode - Binary Tree Inorder Traversal (0) | 2022.09.30 |
---|---|
LeetCode - Longest Common Prefix (0) | 2022.09.30 |
백준 1406 (1) | 2022.09.29 |
백준 2630 (1) | 2022.09.29 |
백준 11279 (0) | 2022.09.29 |
댓글