我正在尝试找到使用不同块用法的最佳性能方式/方法。我正在运行下面的回文程序,用 3 种不同的方式测量每个程序的执行时间。但我总是得到'0'作为输出。我的代码有什么问题。请帮我。
主要的
long startTime, endTime, duration;
startTime = Instant.now().toEpochMilli();
System.out.println(palindromeUsingStringBuilderReverse(str));
endTime = Instant.now().toEpochMilli();
duration = (endTime - startTime);
System.out.println("Duration for using string builder : " + duration);
startTime = Instant.now().toEpochMilli();
System.out.println(palindromeUsingForLoop(str));
endTime = Instant.now().toEpochMilli();
duration = (endTime - startTime);
System.out.println("Duration for using for loop : " + duration);
startTime = Instant.now().toEpochMilli();
System.out.println(palindromeUsingWhile(str));
endTime = Instant.now().toEpochMilli();
duration = (endTime - startTime);
System.out.println("Duration for using while loop : " + duration);
回文使用 StringBuilderReverse
StringBuilder bdr = new StringBuilder(str);
if (str.equalsIgnoreCase(bdr.reverse().toString())) {
return "The given string is a Palindrome.";
} else {
return "This is not a Palindrome string.";
}
回文使用ForLoop
String revStr = "";
for (int i=str.length()-1; i>=0; i--) {
revStr = revStr + str.charAt(i);
}
if (str.equalsIgnoreCase(revStr)) {
return "The given string is a Palindrome.";
} else {
return "This is not a Palindrome string.";
}
回文UsingWhile
int i = 0, j = str.length() - 1;
while (i < str.length()) {
if (str.charAt(i) != str.charAt(j)) {
return "This is not a Palindrome string.";
} else {
i++;
j--;
}
}
return "The given string is a Palindrome.";
慕标5832272
相关分类