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