From 99b8b5744ef3aadb97da6ea9049ed2c1f53dbdc5 Mon Sep 17 00:00:00 2001 From: "Farmer.Chillax" <48387781+FarmerChillax@users.noreply.github.com> Date: Tue, 31 Oct 2023 23:02:44 +0800 Subject: [PATCH] =?UTF-8?q?Update=200242.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D.md?= 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 f47d8b05..6eed90a7 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -181,6 +181,31 @@ func isAnagram(s string, t string) bool { } ``` +Go 写法二(只对字符串遍历一次) +```go +func isAnagram(s string, t string) bool { + if len(s) != len(t) { + return false + } + records := [26]int{} + for index := 0; index < len(s); index++ { + if s[index] == t[index] { + continue + } + sCharIndex := s[index] - 'a' + records[sCharIndex]++ + tCharIndex := t[index] - 'a' + records[tCharIndex]-- + } + for _, record := range records { + if record != 0 { + return false + } + } + return true +} +``` + ### JavaScript: ```js