【简单】回文序列

如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如:
{1, 2, 1}, {15, 78, 78, 15} , {112} 是回文序列,
{1, 2, 2}, {15, 78, 87, 51} ,{112, 2, 11} 不是回文序列。
现在给出一个数字序列,允许使用一种转换操作:
选择任意两个相邻的数,然后从序列移除这两个数,并用这两个数字的和插入到这两个数之前的位置(只插入一个和)。
现在对于所给序列要求出最少需要多少次操作可以将其变成回文序列。

import java.util.Scanner;


public class Main {
    public static boolean check(int[] num,int mid){
        int i = mid;
        int j = mid;
        //System.out.println(mid);
        for(;i>0 && j<num.length-1;i--,j++){
            if(num[i] != num[j]) return false;
            if(num[i]==-1&&num[i]==num[j]) break;
        }
        return true;
    }
    public static int Solution(int[] num){
        int counts = 0;
        int i = 0;
        int j = num.length-1;
        while(i < j){
            if(num[i] < num[j]){
                num[i+1] += num[i];
                num[i] = 0;
                i++;
                counts++;
            }
            else if(num[i] > num[j] ){
                num[j-1] += num[j];
                num[j] = 0;
                j--;
                counts++;
            }else {
                i++;
                j--;
            }
        }
        return counts;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner cin = new Scanner(System.in);
        while(cin.hasNext()){
            int n = cin.nextInt();
            int[] arr = new int[n];
            for(int i=0;i<n;i++){
                arr[i] = cin.nextInt();
            }
            System.out.println(Solution(arr));
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值