Java 中形成回文的最小插入数

2024年9月10日 | 阅读 9 分钟

给定一个字符串。我们的任务是通过插入字符来将该字符串转换为回文串。字符只能插入到输入字符串的最左侧。在输出中,我们需要提及为了使输入字符串成为回文串而插入的字符总数。请参阅以下示例。

示例:1

输入

字符串 str = "ab"

输出 1

解释: 如果我们在字符串的最左侧插入字符 'b',我们得到字符串 "bab",这是一个回文串。因此,插入到输入字符串中的字符总数为 1。

示例:2

输入

字符串 str = "abcd"

输出 3

解释: 如果我们在字符串的最左侧插入字符 'b',我们得到字符串 "dcbabcd",这是一个回文串。因此,插入到输入字符串中的字符总数为 3。

例如:3

输入

字符串 str = "bab"

输出 0

解释: 输入字符串已经是回文串。因此,不需要插入任何字符。输出为 0。

朴素方法

在这种方法中,我们将使用递归。我们将使用一个名为 computeMinInsertions() 的方法来计算使字符串成为回文串所需的最小字符数。请观察以下实现。

文件名: MinInsertionPalindrome.java

输出

For the string: ab
The minimum number of characters that should be inserted to make it palindromic is: 1

For the string: abcd
The minimum number of characters that should be inserted to make it palindromic is: 3

For the string: bab
The minimum number of characters that should be inserted to make it palindromic is: 0

复杂度分析: 程序的时间复杂度为 O(nn),空间复杂度为 O(n),其中 n 是输入字符串中存在的字符总数。

上述程序的时间复杂度非常高,不适用于大型输入。高时间复杂度的原因是许多子问题被反复计算。我们可以通过动态规划来避免子问题的重复计算。以下方法展示了这一点。

方法:使用动态规划

我们将使用一个二维数组来存储子问题的解,以便它们不会被重复计算。此外,我们将使用存储的子问题解来计算最终解。

文件名: MinInsertionPalindrome1.java

输出

For the string: ab
The minimum number of characters that should be inserted to make it palindromic is: 1

For the string: abcd
The minimum number of characters that should be inserted to make it palindromic is: 3

For the string: bab
The minimum number of characters that should be inserted to make it palindromic is: 0

复杂度分析: 由于使用了两个循环(嵌套循环),程序的总时间复杂度为 O(n2)。此外,在 computeMinInsertions() 方法中使用了二维数组,使得程序的空间复杂度为 O(n2),其中 n 是输入字符串中存在的字符总数。

另一种方法:使用最长公共子序列

另一种方法是使用 LCS(最长公共子序列)问题的概念。使用此方法,我们将找到输入字符串及其反序字符串的最长公共子序列。

文件名: MinInsertionPalindrome2.java

输出

For the string: ab
The minimum number of characters that should be inserted to make it palindromic is: 1

For the string: abcd
The minimum number of characters that should be inserted to make it palindromic is: 3

For the string: bab
The minimum number of characters that should be inserted to make it palindromic is: 0

复杂度分析:该程序的时间复杂度和空间复杂度与前一个程序相同。

我们仍然可以对空间复杂度进行优化。请注意,在 LCS 表中,我们只需要当前行和上一行的元素。其说明在以下程序中给出。

文件名: MinInsertionPalindrome3.java

输出

For the string: ab
The minimum number of characters that should be inserted to make it palindromic is: 1

For the string: abcd
The minimum number of characters that should be inserted to make it palindromic is: 3

For the string: bab
The minimum number of characters that should be inserted to make it palindromic is: 0

复杂度分析: 该程序的时间复杂度与前一个程序相同。然而,该程序使用的空间复杂度比前一个程序要好,即 O(N),其中 N 是输入字符串中存在的字符总数。这是因为该程序仅使用了单维数组。