我正在尝试编写一个函数来确定两个字符串是否是彼此的字谜。除了大小写,我给函数两个相等的字符串,它失败了,即使我在比较中忽略了case。
测试用例:
hello
Hello
对于这些输入我的输出不是anagram,但它是anagram
消息来源代码:
static boolean isAnagram(String a, String b) {
char[] a1 = a.toCharArray();
char[] b1 = b.toCharArray();
Arrays.sort(a1);
Arrays.sort(b1);
String x = new String(a1);
String y = new String(b1);
int i=0,flag=0;
while(i < a1.length)
{
if(x.equalsIgnoreCase(y)){
i++;
}
else
return false;
}
return true;
}
答案 0 :(得分:0)
您不需要while循环;
static boolean isAnagram(String a, String b) {
char []a1= a.toLowerCase().toCharArray();
char []b1= b.toLowerCase().toCharArray();
Arrays.sort(a1);
Arrays.sort(b1);
String x= new String(a1), y = new String(b1);
return x.equals(y);
}
答案 1 :(得分:0)
检查以下用于字谜检查的方法:
/**
* Java program - String Anagram Example.
* This program checks if two Strings are anagrams or not
*/
public class AnagramCheck {
/*
* One way to find if two Strings are anagram in Java. This method
* assumes both arguments are not null and in lowercase.
*
* @return true, if both String are anagram
*/
public static boolean isAnagram(String word, String anagram){
if(word.length() != anagram.length()){
return false;
}
char[] chars = word.toCharArray();
for(char c : chars){
int index = anagram.indexOf(c);
if(index != -1){
anagram = anagram.substring(0,index) + anagram.substring(index +1, anagram.length());
}else{
return false;
}
}
return anagram.isEmpty();
}
/*
* Another way to check if two Strings are anagram or not in Java
* This method assumes that both word and anagram are not null and lowercase
* @return true, if both Strings are anagram.
*/
public static boolean iAnagram(String word, String anagram){
char[] charFromWord = word.toCharArray();
char[] charFromAnagram = anagram.toCharArray();
Arrays.sort(charFromWord);
Arrays.sort(charFromAnagram);
return Arrays.equals(charFromWord, charFromAnagram);
}
public static boolean checkAnagram(String first, String second){
char[] characters = first.toCharArray();
StringBuilder sbSecond = new StringBuilder(second);
for(char ch : characters){
int index = sbSecond.indexOf("" + ch);
if(index != -1){
sbSecond.deleteCharAt(index);
}else{
return false;
}
}
return sbSecond.length()==0 ? true : false;
}
}