From a25409d7ec351aaf2e6e513e3e091fc97cd17d60 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Thu, 12 May 2022 19:16:20 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200242.=E6=9C=89=E6=95=88?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D.md=20Sca?= =?UTF-8?q?la=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0242.有效的字母异位词.md | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 080166fd..4f0d143e 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -307,6 +307,31 @@ impl Solution { } } ``` + +Scala: +```scala +object Solution { + def isAnagram(s: String, t: String): Boolean = { + // 如果两个字符串的长度不等,直接返回false + if (s.length != t.length) return false + val record = new Array[Int](26) // 记录每个单词出现了多少次 + // 遍历字符串,对于s字符串单词对应的记录+=1,t字符串对应的记录-=1 + for (i <- 0 until s.length) { + record(s(i) - 97) += 1 + record(t(i) - 97) -= 1 + } + // 如果不等于则直接返回false + for (i <- 0 until 26) { + if (record(i) != 0) { + return false + } + } + // 如果前面不返回false,说明匹配成功,返回true,return可以省略 + true + } +} +``` + ## 相关题目 * 383.赎金信