首页 > 解决方案 > 试图解决这个 Java 问题:finding palindromes (String)

问题描述

我是一名“菜鸟”Java 学生,正在尝试完成下一个问题,即寻找回文。我已经尝试过,但我无法得到解决方案!正如我所说的我是“菜鸟”,我只使用“标准”公共类,我不知道如何解释它,但我还在学习,所以我什至不知道功能是如何工作的,你可以让它复杂,但不要太复杂xD。在这里,谢谢大家:

回文是从左到右和从右到左以相同方式输入的单词,例如:Y、EE、ALA、ANNA、ROTOR 或 AAAAAA

向用户询问一个单词并确定它是否是回文,并显示该单词内部有多少不同的回文。

输入输出示例:

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;
            }
        }
    }
}

标签: java

解决方案


这不是最好的性能解决方案,但这很直观。

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;
}

推荐阅读