简体   繁体   English

在 java 中仅使用字符串 class 检查字谜

[英]Check for an anagram using only the string class in java

I have an assignment to write a program that accepts 2 words and then returns whether they are an anagram of one another.我的任务是编写一个接受 2 个单词的程序,然后返回它们是否是彼此的字谜。 Currently I am trying to loop through every letter of the first one, and check whether it matches with a letter in the second word.目前我正在尝试遍历第一个字母的每个字母,并检查它是否与第二个单词中的字母匹配。 I will then compare the counter int with the total length of either word, which should be equal if they are anagrams.然后,我将计数器 int 与任一单词的总长度进行比较,如果它们是字谜,它们应该相等。

I have an error where currently I get an infinite loop of counting upwards if the words are anagrams, and have a count to the number of letters in the words ending in the program not closing if not.我有一个错误,如果单词是字谜,我目前会无限循环向上计数,并且计算以程序结尾的单词中的字母数,如果不是,则不会关闭。

The assignment states "Use only the methods available in the String class. Do not use other Java library utilities", so I am unable to put the words into an array and use arrays.Sort.分配状态“仅使用字符串 class 中可用的方法。不要使用其他 Java 库实用程序”,所以我无法将单词放入数组并使用 ZA3CBC3F9D0CE2F2C1554E1B671D71D9ZC

import java.util.Scanner;

public class anagram {
  public static void main (String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter two strings");

    String s1 = scanner.next();
    String s2 = scanner.next();


    int counter = 0;

    int number1 = 0;
    int number2 = 0;

    if(s1.length() != s2.length()) {
        System.out.println("The strings are not anagrams");
    }   else {


        for(int i = 0; i < s1.length() ; i++) {
            for(int j = 0; j < s1.length() ; i++) {

                // number1 = i;
                // number2 = j;

                if(i == s1.length()){
                    number1 = i - 1;
                }
                if(j == s2.length()){
                    number2 = j - 1;
                }


                if(s1.charAt(number1) == s2.charAt(number2)) {
                    counter ++ ;
                    System.out.println(counter);
                }

            }

        }
        System.out.println(counter);

    }

    System.out.println(s1 + " " + s2 + " " + counter);

}

} }

Your problem lies here 你的问题就在这里

 for(int j = 0; j < s1.length() ; j++) {   ///change i to j

You are checking n^2 times, however this could be done with only 2n times. 您正在检查n^2次,但是这只能完成2n次。

  1. Get the occurrences of all letters from 1st String (store in array) 从第一个字符串中获取所有字母的出现(存储在数组中)
  2. Get the occurrences of all letters from 2nd String (store in array) 从第二个字符串中获取所有字母的出现(存储在数组中)
  3. Loop through both arrays concurrently and compare whether all occurrences are the same. 同时遍历两个数组,并比较是否所有出现都相同。

Your array will have 26 elements storing the occurrences of az (if case is not sensitive) 您的阵列将具有26个元素存储的发生az (如果情况不敏感)

In the 2nd level of your for-loop, your are incrementing i instead of j. 在for循环的第二级中,您将递增i而不是j。 Because j is never incremented, (j < s1.length) is always true. 因为j从不增加,所以(j <s1.length)始终为true。

import java.util.Scanner;

public class anagram {
  public static void main (String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter two strings");

    String s1 = scanner.next();
    String s2 = scanner.next();


    int counter = 0;

    int number1 = 0;
    int number2 = 0;

    if(s1.length() != s2.length()) {
        System.out.println("The strings are not anagrams");
    }   else {


        for(int i = 0; i < s1.length() ; i++) {
            for(int j = 0; j < s1.length() ; j++) { //LOOK HERE <======

                // number1 = i;
                // number2 = j;

                if(i == s1.length()){
                    number1 = i - 1;
                }
                if(j == s2.length()){
                    number2 = j - 1;
                }


                if(s1.charAt(number1) == s2.charAt(number2)) {
                    counter ++ ;
                    System.out.println(counter);
                }

            }

        }
        System.out.println(counter);

    }

    System.out.println(s1 + " " + s2 + " " + counter);

}
}
public class Main {

    static boolean isAnagram(String a, String b) {
        // Complete the function
        boolean flag = true;
        if (a.length() != b.length())
            return false;
        char str1[] = a.toCharArray();
        char str2[] = b.toCharArray();
        int countstr1[] = countLetters(str1);
        int countstr2[] = countLetters(str2);
        for (int i = 0; i < countstr1.length; i++) {
            if (countstr1[i] != countstr2[i])
                flag = false;
        }

        return flag;
    }

    public static void main(String[] args) {
        String a = "anagram";
        String b = "margana";
        boolean ret = isAnagram(a, b);
        System.out.println((ret) ? "Anagrams" : "Not Anagrams");
    }

    /** Count the occurrences of each letter */
    public static int[] countLetters(char[] chars) {
        // Declare and create an array of 26 int
        int[] counts = new int[26];
        // For each lowercase letter in the array, count it
        for (int i = 0; i < chars.length; i++)
            counts[Character.toLowerCase(chars[i]) - 'a']++;
        return counts;
    }

}

The countLetters method is the real hero in this program. countLetters方法是这个程序中真正的英雄。 This method counts and stores the frequency of each character in an array and returns the array to the calling method.该方法计算每个字符的出现频率并将其存储在一个数组中,并将该数组返回给调用方法。 This program ignores the case and determines whether the two strings are anagrams该程序忽略大小写并确定两个字符串是否为字谜

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM