-1

有人可以向我解释下面的标记线是如何工作的吗?他们具体做什么?

public class GrammerUtils {         

    public static void main(String args[]) {
        System.out.print(isAnagram("teacher", "cheater"));    
    }

    public static boolean isAnagram(String word, String anagram) {
        if (word.length() != anagram.length()) {
            return false;
        }  
        char[] chars = word.toCharArray(); // marked
        for (char c: chars) {              // marked
            int index = anagram.indexOf(c);// marked
            if (index != -1) {             // marked
                anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());
            } else {
                return false;
            }
        }
        return anagram.isEmpty();
    }
}
4

7 回答 7

3

代码在一个接一个的单词中取一个字符

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());

并转到下一个字符(当您检查完单词中的所有字符后,您会检查字谜中的所有字符是否都匹配,即字谜现在是否为空)。

如果字符不在字谜中,则意味着它不是字谜,并且您返回 false。

 return false;

这是相当低效的(O(n ^ 2))。更好地对两个字符串进行排序并比较结果 (O(n*log(n))

于 2013-07-04T15:11:28.730 回答
1

这不能回答您的问题,但渐近地是一种更有效的算法。

public static void isAnagram(String s1, String s2){
    char[] c1 = s1.toLowerCase().toCharArray();
    char[] c2 = s2.toLowerCase().toCharArray();

    Arrays.sort(c1);
    Arrays.sort(c2);

    if(Arrays.equals(c1, c2))
        System.out.println("s1 is anagram of s2");
    else
        System.out.println("Strings are not anagram");
}
于 2017-05-17T19:53:32.003 回答
1

我在不使用索引的情况下尝试了以下方式

package com.learn.java.fileop;

public class Anagram {


        public boolean checkAnagram(String basestr , String anastr){

        char[] ch = basestr.toCharArray();
        char[] ch1 = anastr.toCharArray();

        int asciivalue=0;
        int sum_src=0;
        for(int i =0 ; i< ch.length;i++){
            asciivalue = ch[i];
            sum_src = sum_src+asciivalue;
        }
        System.out.println(""+sum_src);
        int sum_dest=0;
        for(int i = 0 ; i< ch1.length;i++){
            asciivalue = ch1[i];
            sum_dest = sum_dest+asciivalue;
         }

         System.out.println(""+sum_dest);
         if (sum_src == sum_dest){
             return true;
         }else{
             return false;
         }
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Anagram an = new Anagram();
    System.out.println(an.checkAnagram("teacher", "cheater"));
}

}

如果这看起来不错或对此有任何其他想法,请告诉我。

于 2015-09-18T19:48:07.080 回答
0

代码循环遍历word. 对于每个字符,它会检查它是否在anagram. 如果不是,则返回false. 否则,它将删除该字符anagram并移至下一个字符。

public static boolean isAnagram(String word, String anagram) {
    if (word.length() != anagram.length()) {
        return false;
    }  
    char[] chars = word.toCharArray();
    //loop through each character in `word`
    for (char c: chars) {
      int index = anagram.indexOf(c);
        //if it exists in `anagram`, remove it using a combination of `substring` calls, else return false
        if (index != -1) {
          anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());
        } else {
            return false;
        }
    }
    return anagram.isEmpty();
}
于 2013-07-04T15:09:52.527 回答
0

该代码效率也相当低,因为它在 for 循环的每一步都创建了一个新的 String ,并将其重新分配给anagram。下面是一种使用 java.util.Arrays 的方法,其中包含用于操作数组的各种实用方法。最后, isAnagarm() 可能应该是一个静态 util 方法。

public static boolean isAnagram(String s, String t) {
    if (s == null || t == null) {
        return false;
    }

    if(s.isEmpty() && t.isEmpty()) {
        return true;
    }

    char[] sArray = s.toCharArray();
    char[] tArray = t.toCharArray();
    Arrays.sort(sArray);
    Arrays.sort(tArray);

    return Arrays.equals(sArray, tArray);
}
于 2016-08-18T19:14:51.323 回答
0
   Program to check the entered strings are Anagram:

   public class AnagramWordTest {
     public static void main(String[] args) {
     String str1 = "cat";
     String str2 = "tac";

    int not_found=0;
    if(str1.length() == str2.length()) {

        Boolean isDuplicate = 
   testDuplicatesinEachWord(str1.toLowerCase().trim(), 
     str2.toLowerCase().trim());

        if(!isDuplicate) {
            int found=0;
            for (int i = 0; i < str1.length(); i++) {
                for (int j = 0; j < str2.length(); j++) {


                    if(str1.charAt(i) == str2.charAt(j)) {
                        found=1;
                        break;
                    }
                }
                if(found == 0) {
                    not_found=1;
                    break;
                }
            }

            if(not_found==1) {
                System.out.println("The two strings are not Anagrams");
            }else {
                System.out.println("The two strings are Anagrams");

            }
        } else {
            System.out.println("Entered strings has duplicates to check 
            Anagrams in either");
        }

    }else {
        System.out.println("String lengths are different and are not 
         Anagram");
    }
   }

  private static boolean testDuplicatesinEachWord(String str1, String str2) 
  {
    Boolean isStr1Duplicate = false;
    Boolean isStr2Duplicate = false;
    Boolean isDuplicate = false;
    for(int k=0;k<str1.length();k++) {
        for(int m=k+1;m<str1.length()-1;m++) {
            if(str1.charAt(k) == str1.charAt(m)) {
                isStr1Duplicate = true;
                break;
            }
        }
    }

    for(int l=0;l<str2.length()-1;l++) {
        for(int n=l+1;n<str1.length()-1;n++) {
            if(str1.charAt(l) == str2.charAt(n)) {
                isStr2Duplicate = true;
                break;
            }}
    }

    if(isStr1Duplicate.equals(Boolean.TRUE) || 
        isStr2Duplicate.equals(Boolean.TRUE)) {
        isDuplicate= true;
    }
    return isDuplicate;
    }
  }
于 2019-05-24T15:21:36.420 回答
-1

// 导入有助于我们操作数组的 Arrays 类。导入 java.util.Arrays;

公共类 AnagramTest {

private static boolean isAnagram(String str1 , String str2){
        // Converting both strings to char arrays as strings do not have direct
        // sorting method in java.
        char [] leftArray = ( str1.trim().toLowerCase()).toCharArray();
        char [] rightArray = ( str2.trim().toLowerCase()).toCharArray();
        Arrays.parallelSort(leftArray); // Sorting the array using the java 8 
        Arrays.parallelSort(rightArray);// parallelSort method

        return Arrays.equals(leftArray, rightArray);
    }               
public static void main(String [] args){
        //Test cases;
        String a = "integral"; // initializing first string
        String b = "Triangle"; // initializing second string
        System.out.println("The statement "+ a + " is anagram of "+b+" is "+isAnagram(a,b));// Print true

        String c = "silent"; // initializing first string
        String d = "listen"; // initializing second string
        System.out.println("The statement "+ c + " is anagram of "+d+" is "+isAnagram(c,d));// Print true

        String e = "fried"; // initializing first string
        String f = "fired"; // initializing second string
        System.out.println("The statement "+ e + " is anagram of "+f+" is "+isAnagram(e,f));// true            
        String g = "ball"; // initializing first string
        String h = "call"; // initializing second string
        System.out.println("The statement "+ g + " is anagram of "+h+"is "+isAnagram(g,h));// Print false                       
    }           

}

于 2020-04-04T19:15:54.433 回答