刚刚完成了最近的作业,但我知道它可能会更有效率。它从命令行中读取两个单词,忽略空格和标点符号,并确定它们是否是变形词。我所拥有的是下面的;据我所知,它是全功能的。
/**
* Find out if a string is an anagram of another string
*
*/
import java.util.Arrays;
public class Anagram
{
public static void main(String[] args)
{
if (args.length != 2)
System.out.println("You did not enter two words!");
else
printWords(args[0], args[1]);
}
// method to determine whether two strings have the same chars
public static boolean areAnagrams(String wordOne, String wordTwo)
{
// new strings for letters only
String ltrsOnlyOne = lettersOnly(wordOne);
String ltrsOnlyTwo = lettersOnly(wordTwo);
// convert strings to lowercase char arrays
char[] first = ltrsOnlyOne.toLowerCase().toCharArray();
char[] second = ltrsOnlyTwo.toLowerCase().toCharArray();
// sort char arrays using sort method
Arrays.sort(first);
Arrays.sort(second);
if (Arrays.equals(first, second))
return true;
else
return false;
}
public static String lettersOnly(String word)
{
int length = word.length();
StringBuilder end = new StringBuilder(length);
char x;
for (int i = (length - 1); i >= 0; i--) {
x = word.charAt(i);
if (Character.isLetter(x)) {
end.append(x);
}
}
return end.toString();
}
public static void printWords(String wordOne, String wordTwo)
{
boolean b = areAnagrams(wordOne, wordTwo);
if (b == true) {
System.out.println(wordOne + " is an anagram of "+ wordTwo);
}
if (b == false) {
System.out.println(wordOne + " is not an anagram of "+ wordTwo);
}
}
}发布于 2010-11-06 12:30:07
O(n * log n)复杂性),并在线性(O(n))时间内解决问题。/** ... */)的javadoc注释应该紧跟在类声明(public class ...)之前。现在,在javadoc注释和类声明之间有一条导入语句。发布于 2010-11-06 12:12:53
我会将santize步骤lettersOnly()移到sameChars()之外的一个单独的方法中,从main调用。它不是更高效,但它的代码更干净:
public static void main(String[] args)
{
if (args.length != 2) {
System.out.println("You did not enter two words!");
}
String wordOne = lettersOnly(args[0]);
String wordTwo = lettersOnly(args[1]);
printWords(wordOne, wordTwo);
}
// method to determine whether two strings have the same chars
public static boolean sameChars(String wordOne, String wordTwo)
{
// convert strings to lowercase char arrays
char[] first = wordOne.toLowerCase().toCharArray();
char[] second = wordTwo.toLowerCase().toCharArray();
Arrays.sort(first);
Arrays.sort(second);
return Arrays.equals(first, second);
}
public static void printWords(String wordOne, String wordTwo)
{
boolean isAnagram = sameChars(wordOne, wordTwo);
if (isAnagram)
{
System.out.println(wordOne + " is an anagram of "+ wordTwo);
}
else
{
System.out.println(wordOne + " is not an anagram of "+ wordTwo);
}
} 发布于 2010-11-06 12:16:10
您只需要调用sameChars一次。否则,在false情况下,您将小写并迭代数组两次。尝试:
public static void printWords(String wordOne, String wordTwo)
{
boolean same = sameChars(wordOne, wordTwo);
if (same) {
System.out.println(wordOne + " is an anagram of "+ wordTwo);
} else {
System.out.println(wordOne + " is not an anagram of "+ wordTwo);
}
}https://stackoverflow.com/questions/4111810
复制相似问题