我只是想问一下我的代码有什么问题,因为它没有输出2个单词是anagram。感谢任何帮助。
公共课程计划{public static void main(String[] args){
String word1 ="test";
String word2 = "tset";
boolean output = isAnagram(word1,word2);
System.out.println("isAnagram:"+output);
}
public static boolean isAnagram(String word1, String word2){
boolean output = false;
boolean found = false;
int x = 0;
int ctr = 0;
for(int i=0; i<word1.length()-1;i++){
x=0;
found=false;
while(found!=true){
if(word1.charAt(x)==word2.charAt(i)){
ctr++;
found=true;
}
else{
x++;
}
}}
if(ctr==word1.length()&&ctr==word2.length()){
output = true;
}
return output;
}}
答案 0 :(得分:0)
public static boolean isAnagram(String word1, String word2){
boolean isAnagram = false;
int x = 0;
int ctr = 0;
if(word1.length() == word2.length()){
int n = 0;
for(int c = word2.length(); c > 0 && n < word2.length() , c++ ){
if(word1.charAt(n).equals(word2.charAt(c))){
x++;
}
n++;
}
if(x == word1.length())
isAnagram == true;
}
return isAnagram;
}}
这将取第一个和最后一个字母或字符,并在第二个字母上计数,并在第二个字母上计数。