[英]in Valid Anagram program not passing all test cases
Given two strings s and t, write a function to determine if t is an anagram of s.给定两个字符串 s 和 t,写一个 function 来确定 t 是否是 s 的变位词。
Example 1:示例 1:
Input: s = "anagram", t = "nagaram" Output: true Example 2:输入:s = "anagram", t = "nagaram" Output: true 示例 2:
Input: s = "rat", t = "car" Output: false输入:s = "老鼠", t = "汽车" Output: false
example 3 "aad" "cab" Output true Expected false示例 3 "aad" "cab" Output true 预期 false
my 3 test case is giving output true why?我的 3 个测试用例给出 output true 为什么?
class Solution {
public boolean isAnagram(String s, String t) {
if (s.isEmpty() && t.isEmpty()) {
return true;
}
if (s.length() != t.length()) {
return false;
}
char[] a = s.toCharArray();
char[] b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
for (int i = 0; i <= a.length; i++) {
for (int j = 0; j <= b.length; j++) {
if (a[i] == b[j]) {
return true;
}
}
}
return false;
}
}
By using a nested for loop, you will iterate over every possible pair (i, j) with i and j an in idex in a
and b
respectively.通过使用嵌套的 for 循环,您将迭代每个可能的对(i, j) ,其中i和j an 分别位于
a
和b
中的 idex 中。 Furthermore you use i++
and j++
twice, and thus you will skip the even indices.此外,您使用
i++
和j++
两次,因此您将跳过偶数索引。 You can not return true
from the moment a[i++] == b[j++]
matches.从
a[i++] == b[j++]
匹配的那一刻起,您就不能返回true
。 In order to know if something is an anagram, you need to iterate over all elements.为了知道某物是否是字谜,您需要遍历所有元素。 You can return
false
from the moment a[i] != b[i]
however.但是,您可以从
a[i] != b[i]
的那一刻起返回false
。 Finally the bound should be i < a.length
, not i <= a.length
.最后边界应该是
i < a.length
,而不是i <= a.length
。
You thus need one for
loop where you make a single increment and compare a[i]
with b[i]
:因此,您需要一个
for
循环,在其中进行单个增量并将a[i]
与b[i]
进行比较:
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()){
return false;
}
char[] a = s.toCharArray();
char[] b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
for(int i = 0; i < a.length; i++) {
if(
a[i] != b[i]) {
return
false;
}
}
return
true;
}
You are just comparing the first letter of cab and rat which is a , and returning True, actually you need to check all letters.您只是比较cab和rat的第一个字母a ,并返回 True,实际上您需要检查所有字母。
Hence make the condition negative and swap the returns.因此,使条件为负并交换收益。
if(a[i++] !=b[j++]){
return false;
}
return true;
The above code will return false, when characters aren't equal, hence the last line is reached only when all chars are equal.当字符不相等时,上面的代码将返回 false,因此只有当所有字符都相等时才会到达最后一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.