我有一个程序,向您显示两个单词是否互为字母。有一些示例将无法正常工作,我将不胜感激,尽管如果它不先进,那将是很棒的,因为我是一名1年级程序员。“校长”和“教室”是彼此的字谜,但是当我将“教室”更改为“ theclafsroom”时,仍然说它们是字谜,我在做什么错?
import java.util.ArrayList; public class AnagramCheck { public static void main(String args[]) { String phrase1 = "tbeclassroom"; phrase1 = (phrase1.toLowerCase()).trim(); char[] phrase1Arr = phrase1.toCharArray(); String phrase2 = "schoolmaster"; phrase2 = (phrase2.toLowerCase()).trim(); ArrayList<Character> phrase2ArrList = convertStringToArraylist(phrase2); if (phrase1.length() != phrase2.length()) { System.out.print("There is no anagram present."); } else { boolean isFound = true; for (int i=0; i<phrase1Arr.length; i++) { for(int j = 0; j < phrase2ArrList.size(); j++) { if(phrase1Arr[i] == phrase2ArrList.get(j)) { System.out.print("There is a common element.\n"); isFound = ; phrase2ArrList.remove(j); } } if(isFound == false) { System.out.print("There are no anagrams present."); return; } } System.out.printf("%s is an anagram of %s", phrase1, phrase2); } } public static ArrayList<Character> convertStringToArraylist(String str) { ArrayList<Character> charList = new ArrayList<Character>(); for(int i = 0; i<str.length();i++){ charList.add(str.charAt(i)); } return charList; } }
最快的算法是将26个英文字符中的每一个映射到唯一的质数。然后计算字符串的乘积。根据算术的基本定理,当且仅当它们的乘积相同时,两个字符串才是字谜。