mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 21:10:58 +08:00
update 0242.有效的字母异位词:加java注释,删除质量较差且多余的go代码
This commit is contained in:
@ -101,7 +101,7 @@ class Solution {
|
||||
int[] record = new int[26];
|
||||
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
record[s.charAt(i) - 'a']++;
|
||||
record[s.charAt(i) - 'a']++; // 并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
|
||||
}
|
||||
|
||||
for (int i = 0; i < t.length(); i++) {
|
||||
@ -109,11 +109,11 @@ class Solution {
|
||||
}
|
||||
|
||||
for (int count: record) {
|
||||
if (count != 0) {
|
||||
if (count != 0) { // record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
return true; // record数组所有元素都为零0,说明字符串s和t是字母异位词
|
||||
}
|
||||
}
|
||||
```
|
||||
@ -166,35 +166,10 @@ class Solution(object):
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
func isAnagram(s string, t string) bool {
|
||||
if len(s)!=len(t){
|
||||
return false
|
||||
}
|
||||
exists := make(map[byte]int)
|
||||
for i:=0;i<len(s);i++{
|
||||
if v,ok:=exists[s[i]];v>=0&&ok{
|
||||
exists[s[i]]=v+1
|
||||
}else{
|
||||
exists[s[i]]=1
|
||||
}
|
||||
}
|
||||
for i:=0;i<len(t);i++{
|
||||
if v,ok:=exists[t[i]];v>=1&&ok{
|
||||
exists[t[i]]=v-1
|
||||
}else{
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
```
|
||||
|
||||
Go写法二(没有使用slice作为哈希表,用数组来代替):
|
||||
|
||||
```go
|
||||
func isAnagram(s string, t string) bool {
|
||||
record := [26]int{}
|
||||
|
||||
for _, r := range s {
|
||||
record[r-rune('a')]++
|
||||
}
|
||||
@ -202,7 +177,7 @@ func isAnagram(s string, t string) bool {
|
||||
record[r-rune('a')]--
|
||||
}
|
||||
|
||||
return record == [26]int{}
|
||||
return record == [26]int{} // record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user