java - 尝试解决此 Java 问题 : finding palindromes (String)

标签 java

我是一名“菜鸟”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/

相关文章:

JavaFX GUI 多线程问题

java - Android Studio Robolectric 单元测试 - 默认值无效

java - 如何根据目标点确定 2 个臂段的旋转?

java - 使用 easymock 收到错误

java - Oracle 嵌套表作为 Mybatis 存储过程的输入参数

Java:JSON(Gson)从JSON字符串获取值

java - BufferedReader.readLine() 等待来自控制台的输入

java - 在 Bukkit 中从原理图中设置 block 数据?

java - 不同类型接口(interface)的两种实现——这不可能吗?

用于获取东部日期和时间作为日期格式插入数据库的Java代码