gpt4 book ai didi

java - 从给定的字符串中获取所有可能的回文

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:00 25 4
gpt4 key购买 nike

子字符串是字符串中连续的字符范围。

现在我需要找出有多少个可以重新排列的子串可以形成一个回文。

例如:输入-aabb

a
aa
aab (because after re-arranging it becomes aba)
aabb (because after re-arranging it becomes abba)
a
abb (because after re-arranging it becomes bab)
b
bb
b

So we have 9 substring palindromes.

这是我试过的代码:

public static int getPalindromeCount(String str) {
// all single characters are treated as palindrome
int count = str.length();

// Get all sub strings
List<String> subs = new ArrayList<>();
subString(str, subs);

for (String sub : subs) {
String rev = new StringBuilder(sub).reverse().toString();

if (rev.equals(sub)) {
System.out.println(sub);
count++;
} else {
boolean valid = isPalindrome(sub);
System.out.println(sub + " : " + valid);
if (valid) {
count++;
}
}
}
return count;
}

// Check if substring can form a Palindrome
private static boolean isPalindrome(String input) {
Set<Character> oddChars = new HashSet<>();

for (char c : input.toCharArray()) {
if (!oddChars.add(c)) {
oddChars.remove(c);
}
}
return oddChars.size() <= 1;
}

// Get all substrings
private static void subString(String input, List<String> list) {
for (int i = 0; i < input.length(); i++) {
for (int j = i + 2; j <= input.length(); j++) {
list.add(input.substring(i, j));
}
}
}

方法 isPalindrome 我从这篇文章中获取的部分逻辑 Check if a permutation of a string can become a palindrome

此代码运行良好,但因超时错误而失败。

我不确定失败的输入是什么,因为它们隐藏在我的 hackerrank 挑战中。

编辑:

我修改了我的 getPalidromeCount 方法来检查输入中有多少个奇数字母来决定回文数。

这是基于对这篇文章的评论:

Hint: A palindrome consists of all letters of even count or all letters of even count with one letter of odd count(the middle character). Now, you could count possible palindromes easily. – vivek_23

public static int getPalindromeCount(String str) {
List<Integer> list = new ArrayList<>(strToEvaluate.size());
for (String str : strToEvaluate) {
int count = str.length();

List<String> subs = new ArrayList<>();
subString(str, subs);
for (String sub : subs) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < sub.length(); i++) {
char c = sub.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
int odds = 0;
for (char key : map.keySet()) {
if (map.get(key) % 2 != 0) {
odds++;
if (odds > 1) {
break;
}
}
}
if (odds <= 1) {
System.out.println(sub);
count++;
}

list.add(count);
}
}
return list;
}

但我仍然看到超时错误。我没有在此逻辑中使用 isPalindrome 方法。

最佳答案

n(n+1)/2 个可能的子串,对于每个子串,您检查它是否可以重新排列,以便在 O(k)< 中形成回文 其中 k 是给定子字符串的长度,让我们考虑是否有必要分别解析每个子字符串。

提示:

假设您有从索引 pk 的子字符串,对于从索引 pk + 的子字符串,您能说些什么? 1。真的有必要单独解析这个扩展子串吗?

关于java - 从给定的字符串中获取所有可能的回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56989233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com