我是一名“菜鸟”Java 学生,正在尝试完成下一个问题,它是关于查找回文的。我已经尝试这样做,但我无法得到解决方案!正如我所说,我是“菜鸟”,我只使用“标准”公共(public)类,我不知道如何解释它,但我仍在学习,所以我什至不知道这些功能是如何工作的,你可以让它变得复杂,但不能太复杂xD。就这样,谢谢大家:
A palindrome is a word that is typed the same way from left to right and also from right to left, for example: Y, EE, ALA, ANNA, ROTOR or AAAAAA
Ask a word to the user and identify if it is a palindrome or not, and also show how many diferent palindromes the word has inside.
I/O examples:
Write the word:
rotor
Palindromes found apart from the 5 letters that compose the word:
rotor
oto
Total number of palindromes: 7
Write the word:
rotoro
Palindromes found apart from the 5 letters that compose the word:
rotor
oto
oro
Total number of palindromes: 9
Write the word:
AAAAAAAABAA
Palindromes found apart from the 11 letters that compose the word:
AA
AAA
AAAA
AAAAA
AAAAAA
AAAAAAA
AAAAAAAA
AA
AAA
AAAA
AAAAA
AAAAAA
AAAAAAA
AA
AAA
AAAA
AAAAA
AAAAAA
AA
AAA
AAAA
AAAAA
AA
AAA
AAAA
AA
AAA
AA
AABAA
ABA
AA
Total number of palindromes: 31
import java.util.Scanner;
public class palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Write the word: ");
String word = sc.next();
sc.close();
System.out.println();
String subWord = "--";
int increment = 0;
int decrement = word.length();
while (increment < decrement && subWord.length() > 1) {
increment++;
decrement--;
subWord = word.substring(increment, decrement);
for (int i = 0, j = subWord.length() - 1, f = 0, g = 1; f != g && i < j; i++, j--) {
if (subWord.charAt(i) == subWord.charAt(j)) {
System.out.println(subWord);
}
g = f;
}
}
}
}
最佳答案
这不是最佳性能解决方案,但很直观清晰。
public static void main(String[] args) {
System.out.println(countPalindromes("AAAAAAAABAA")); // 42
}
public static int countPalindromes(String str) {
int res = 0;
for (int i = 0; i < str.length(); i++)
for (int j = i + 1; j <= str.length(); j++)
if (isPalindrome(str.substring(i, j)))
res++;
return res;
}
public static boolean isPalindrome(String str) {
for (int i = 0, j = str.length() - 1; i < j; i++, j--)
if (str.charAt(i) != str.charAt(j))
return false;
return true;
}
关于java - 尝试解决此 Java 问题 : finding palindromes (String),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65128927/