完美的代价

基础练习 完美的代价  
时间限制:1.0s   内存限制:512.0MB
   
问题描述
  回文串,是一种特殊的字符串,它从左往右读和从右往左读是一样的。小龙龙认为回文串才是完美的。现在给你一个串,它不一定是回文的,请你计算最少的交换次数使得该串变成一个完美的回文串。
  交换的定义是:交换两个相邻的字符
  例如mamad
  第一次交换 ad : mamda
  第二次交换 md : madma
  第三次交换 ma : madam (回文!完美!)
输入格式
  第一行是一个整数N,表示接下来的字符串的长度(N <= 8000)
  第二行是一个字符串,长度为N.只包含小写字母
输出格式
  如果可能,输出最少的交换次数。
  否则输出Impossible
样例输入
5
mamad
样例输出
3

import java.util.Scanner;

public class BASIC19 {
public static char[] swap(char[] t,int e,int end){
char a=t[e];
for(int i=e;i<end;i++ ){
t[i]=t[i+1];//相邻交换
}
t[end]=a;
return t ;
}
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
String str=scan.next();
char[] t=new char[n];
for(int i=0;i<n;i++){
t[i]=str.charAt(i);
}
int front=0, end=n-1,time=0;
boolean oddNum=false;
while(front<end){
for(int i=end;front<=i;i–){
if(ifront){
if(n%2
0||oddNum){
System.out.print(“Imopssible”);
System.exit(0);
}else{
oddNum=true;
time+=(n/2)-front;
front++;
break;

		}
		}
		if(t[i]==t[front]){
			t=swap(t,i,end);
			front++;
			time+=end-i;
			end--;
			break;
		}
		
	}
	

}
System.out.print(time);

}
/* static char[] swap(char[] chars,int f,int e){//将f处的字符交换到e处
char t=chars[f];
for(int i=f;i<e;i++){
chars[i]=chars[i+1];
}
chars[e]=t;
return chars;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N = sc.nextInt();
String s=sc.next();
char[] chars = new char[N];
for(int i=0;i<N;i++){
chars[i] = s.charAt(i);
}

    int front=0,end=N-1,times=0;
    boolean oddNum = false;
    while(front < end){
        for(int i = end;i>=front;i--){
            if(i == front){//如果没找到和front处相同的字符,即front处是一个出现次数为奇数的字符
                if(N%2==0 || oddNum){
                    System.out.println("Impossible");
                    System.exit(0);
                }else{
                    times += (N/2)-front;
                    oddNum=true;
                    front++;
                    break;
                }
            }
            if(chars[i] == chars[front]){//如果找到,那么交换
                chars = swap(chars,i,end);
                times += end-i;
                front++;end--;
                break;
            }
        }
    }
    System.out.println(times);
}
*/

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值