gpt4 book ai didi

java - 在数组列表中搜索回文数。如果列表中存在回文数,则返回其大小

转载 作者:行者123 更新时间:2023-11-30 05:46:56 25 4
gpt4 key购买 nike

检查列表中是否存在回文数。 如果找到返回其大小,否则返回-1。

public class Program{
public static boolean palindrome(String list){
String reversedString = "";
for (int i = list.length() -1; i >=0; i--){
reveresedString += list.charAt(i)
}
return list.equals(revereseString);
}
}

sample input: [3,5,2,6,3,6,2,1]
palindrome number found: [2,6,3,6,2]
sample output: 5

最佳答案

这是一个伪代码。

output = -1;
for (i = 0; i < list.length; i++){
num = list[i];
indices[] = \\ get all the indices which the "num" value appears, only include those indices that are greater than "i"
for (j = 0; j < indices.length; j++){
flag = true;
k = i;
for (l = indices[j]; l >= k; l--, k++){
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag){
length = (indices[j] - i) + 1;
if (length != 1 && length > output) { // checking of length != 1 will exclude those palindromes of length 2
output = length;
}
}
}
}
return output;

这是完整的代码。

public class Main {

/**
* @param args
*/
public static void main(String[] args) {
int[] list = { 3, 5, 2, 2, 6, 3, 6, 3, 6, 3, 6, 2, 2, 1 };
System.out.print(palindrome(list));
}

public static int palindrome(int[] list) {
int output = -1;
for (int i = 0; i < list.length; i++) {
int num = list[i];
ArrayList<Integer> indices = getIndices(list, i, num);
for (int j = 0; j < indices.size(); j++) {
boolean flag = true;
int k = i;
for (int l = indices.get(j); l >= k; l--, k++) {
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag) {
int length = (indices.get(j) - i) + 1;
if (length != 1 && length > output) {
output = length;
}
}
}
}
return output;
}

public static ArrayList<Integer> getIndices(int[] list, int start, int num) {
ArrayList<Integer> result = new ArrayList<Integer>();

for (int i = start + 1; i < list.length; i++) {
if (list[i] == num) {
result.add(i);
}
}

return result;
}

}

关于java - 在数组列表中搜索回文数。如果列表中存在回文数,则返回其大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54662584/

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