【问题标题】:Compare if 2 strings are anagram to each other比较 2 个字符串是否相互变位
【发布时间】:2015-10-28 19:29:21
【问题描述】:

我只是想问一下我的代码有什么问题,因为它没有输出这两个单词是字谜。感谢任何帮助,谢谢。

公开课程序{

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;
    }}   

【问题讨论】:

标签: java


【解决方案1】:
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;
}}   

这需要第一个和最后一个字母或字符,并从第二个开始倒计时,从第二个开始计数。

【讨论】:

    猜你喜欢
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 2019-11-10
    • 1970-01-01
    • 2010-12-20
    相关资源
    最近更新 更多