字谜 java 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17473513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:06:41  来源:igfitidea点击:

Anagram java code

javaanagram

提问by Namenone

Can someone explain to me how the marked lines below work? What do they do exactly?

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

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

回答by Jirka

The code takes one character in the word after another

该代码在单词中一个接一个字符

char[] chars = word.toCharArray();
for (char c: chars) {

and checks if it is in the potential anagram.

并检查它是否在潜在的字谜中。

int index = anagram.indexOf(c);

If yes

如果是

if (index != -1) {

then removes it so that it is not checked again in case there are repetitions (you take the substring before the character and the substring after the character, keep in mind that substring is exclusive in the second parameter):

然后将其删除,以便在出现重复时不再检查它(您取字符之前的子字符串和字符之后的子字符串,请记住,子字符串在第二个参数中是独占的):

 anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());

and goes to the next character (When you finish checking all characters in the word, you check if all the characters in the anagram were matched, i.e. if the anagram is now empty).

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

If the character is not in the anagram then it means it is not an anagram, and you return false.

如果该字符不在字谜中,则表示它不是字谜,您将返回 false。

 return false;

This is rather inefficient (O(n^2)). Better to sort both strings and compare the results (O(n*log(n))

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

回答by ChandraSPola

i tried it the below way without using indexes

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

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

}

Please let me know if this looks ok or any other thoughts on this.

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

回答by Nik's

This doesn't answer your question, but is asymptotically a more efficient algorithm.

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

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

回答by satish hiremath

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

回答by Yu Chen

The code is rather inefficient also in the sense that it creates a new String in every step of the for loop, and reassign it to anagram. Below is a way using java.util.Arrays, which contains various utility methods for manipulating arrays. And last, isAnagarm() likely should be a static util method.

该代码在 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);
}

回答by go-oleg

The code loops through every character of word. For each character, it checks to see if its in anagram. If its not, it returns false. Otherwise, it removes the character from anagramand moves on to the next character.

代码循环遍历 的每个字符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();
}

回答by Jeancy Tshibemba Mukendi

// Importing the Arrays class that will help us manipulate arrays. import java.util.Arrays;

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

public class AnagramTest {

公共类 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                       
    }           

}

}