iT邦幫忙

2025 iThome 鐵人賽

DAY 4
0

242 Valid Anagram

  • 判斷兩個字串是否為字母異位詞(相同字母但排列不同)。
  • kotlin
class Solution {
    fun isAnagram(s: String, t: String): Boolean {
        if (s.length != t.length) return false
        val count = IntArray(26)
        for (c in s) count[c - 'a']++
        for (c in t) count[c - 'a']--
        return count.all { it == 0 }
    }
}

  • follow up
    • 如果字母不是只有 a-z,而是 Unicode 字元,如何修改?(用 HashMap<Char, Int> 代替 IntArray)
    • 如果字串長度非常大(10^7),怎麼處理?(考慮 streaming + hash,或分批統計)
    • 如果題目變成「找出所有異位詞 group」(延伸題:LeetCode 49 Group Anagrams)?

上一篇
#05
下一篇
#07
系列文
來都來了-涮就涮吧8
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言