在数组列表中搜索回文数。如果列表中存在回文数,return它的大小

search palindrome number in a list of array. if there exist palindrome number in the list, return its size

检查列表中是否存在回文数。 如果找到 return 它的大小,否则 return -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;
    }

}