完美的代价

蓝桥杯基础练习:

问题描述
  回文串,是一种特殊的字符串,它从左往右读和从右往左读是一样的。小龙龙认为回文串才是完美的。现在给你一个串,它不一定是回文的,请你计算最少的交换次数使得该串变成一个完美的回文串。
  交换的定义是:交换两个相邻的字符
  例如mamad
  第一次交换 ad : mamda
  第二次交换 md : madma
  第三次交换 ma : madam (回文!完美!)
输入格式
  第一行是一个整数N,表示接下来的字符串的长度(N <= 8000)
  第二行是一个字符串,长度为N.只包含小写字母
输出格式
  如果可能,输出最少的交换次数。
  否则输出Impossible
样例输入
5
mamad
样例输出
3
【分析】:首先要判断该字符串能不能变成回文串,如果不能你去进行操作就是在浪费时间了,所以判断依据就是统计该字符串中的各字符个数为奇数的个数,如果为奇数的字母个数大于1个,说明整个字符串到最后会有两个落单的字母,肯定不能凑成回文串了,所以这种情况直接“Impossible”就可以了。如果能成为回文串的话,就写一个函数进行递归求解。
 1 import java.util.Scanner;
 2 
 3 public class Main{
 4     public static void main(String args[]){
 5         Scanner sc = new Scanner(System.in);
 6         int N = sc.nextInt();
 7         String string = sc.next();
 8         if(isPossible(string)){    
 9             System.out.println(getResult(string));
10         }else {
11             System.out.println("Impossible");
12         }
13         sc.close();
14     }
15     
16     private static boolean isPossible(String str){
17         int odds = 0;
18         boolean ans = true;
19         int[] temp = new int[26];
20         for(int i=0;i<str.length();i++){
21             temp[str.charAt(i) - 'a']++;
22         }
23         for(int j=0;j<26;j++){
24             if(temp[j] % 2 == 1){
25                 odds++;    
26             }
27         }
28         if(odds > 1){
29             ans = false;
30         }
31         return ans;
32     }
33     
34     private static int getResult(String str){
35         int length = str.length();
36         if(length == 1 || length == 2){
37             return 0;
38         }
39         
40         int temp = str.lastIndexOf(str.charAt(0));
41         if(temp == 0){    //说明这个是除了自己没有找到相同的字母与之匹配了,所以这个需要放到整个字符串的中间。
42             return length/2 + getResult(str.substring(1,length));
43         }else {
44             StringBuffer sb = new StringBuffer(str);
45             sb.deleteCharAt(0);
46             sb.deleteCharAt(temp);
47             return length-1-temp + getResult(sb.toString());
48         }
49     }
50     
51 }
View Code

【PS】:就这样就结束了吗?来看个样例!

输入:
6411
sappytuikoulwwzcdyykjigdynflzrbgffqfkpzzsbfnampapwsmsgtqylggqykoyqltfefkbytkreaybkiqamzxpoefmewfkxezuyqqdqtafgliflgfhhvcwcidfxfxymykkiweifeoceeqhzmiemldhpfgpwwehwrnrudplsgxemvcukkjnbijaqodifjsfbdbonepsdkxegwoqfcyartakjwssimelxzwvpangaknsdravlvryyolpikgwpcolpfafsjzurfwpwookfzeadyhmsyoycmtggjvdmkssejwfwoxpcfkuxvzrbusnqdctlkfjqkuuzqaqdojgknyjcdwdiknjzgswqerddyplpdqjmlqwvvkfsnrampmzokzcozdtxyzottpktwkuyrbmcargygsvkcqzkhgzcxiigabicpfdbtybrcshsimfjxlaxhefnjghcvxgxnigpjpyxninaivtmhaszwxnxbudyiqffzzasnqgxrwhpoerkrdblqwaykczhdoptnhjzadlcrvndstsswrpwdqfumramzttajjwuamhzkxkjmwjuluzikkrxiybukxmzomcyyvpdxjlcnanpccyulztofgeylmtcgucpgkpejiwoonbwmkmcrsntutviafkpqrrrjqqlgefopsvtrwajxykjlzejmeystpuhceyeydobmosbvhwjlrwqtsflfqwsfxieovpzfckvlmlrftvwkqtehuedvgmxasfqvgtcagzbginipwpmrtzpaqllvkmgsqifgbskpakafgdfygwmexattappgcphdbztwbrtjcywonvweooypwebqucjcofuuqcgwoglndynyhvvafpjksdtayrtfxomihonqbplkomlfeykmqkcixwjznwcoshwmjfvduuymrmqrzxvivjtbbvyxwjlzfantrlexmmzayhgizsrknfpruzfydqngctgzhqdrjskodqndepjctylqezpoglzmterqyvqbnkcafnuyqlhcjfulivmloeppzasrccbkuliwsibwmmqxiagkkgoddduokpesjkxjssavowtcojymmadnsyxejdfhwyjpeypdlgptfbfsursrnapnhlngynsrliudvdkghpcitdpeztkshhtrmvdhbriimbfzjfaidpgoeboixeeclpktdnazxwgfzpywjsnrzxhhxqdekxmakvcmhfsszxgelwzsznngmsnxmwvbhqbcjfyfxrnssaqyulymlsffrwqbqxebezmekkphwpdhvpxmjelrbktvvwkylxrseejefeprjqrgojokwrzmtztptdzjiwxwlzqrrpynzflrqnskrxgtpdyhpulotnbpxbyhfnjafgqwfxlwasvbbkcezuomworxjaspxwbwlecuwegzjvmojvedsnauaagbjflwexvwujjktesgwkwvgajevghsvntornhlihpxnoflslgnfxempzpvzysnuloresuhxdkjxrjpororzobkmxccxfvoqcnipbwfaiwaiyjqwzlbkkemthmvwxletndxmzjwdjgfharrsregupxtpfzxvquikiqpxjnpquzzddlntsnbitaestbtjxyglrkgriuddweiejdyomelhsbfyxrgqpulwwqpiewpylhwekejwmtovliclxkbikubvmbtfwzkzbtpxrehkfyvxkmappaddiwcczwtypoitaabayepamoxldhmeezjxaqptyhlvnzsplbtbibrcrlkblnqbdlbwnvmaioyqpxbaeijbhavvxnspjqtwcolomyyxaiblhizmexplkpqsjibbpxpcegmzliadlonijvpnfyzowushrwrzvridzzdklnrvdlrpqeteoyehelovnicjzfphmswzncxxkmegvgohwdpecpavlgjclucqnuwdxzrtdrevjwmggryqfmzplcwuiuggtglgfveiuuzjkladcnfhfkqheudqqbaawjxeogsbabwxzvwopvzsbatxbucqvenhcnbuvmfvkfizmclwmiciqagvrwsufoejbdwamdzefypypuahjeobovoebtylwrpigmncfxjychvcpxwmfjqxkytpawxgubbqgwtacdakdytmpoenfhfmngnccdcwoxrwzqhnbexmsespdduyqxyccwywdipsrkfbhvrjafasunmlbbmeleljznitrqsudmccicvdgelianrbyozqfnemvgzvejtynztygmfxlvwaoizejelyzkfmkblxhfxzimsybwwlpbaeswojyqoolebmjxvaulwklllftzyxtnmhhpqolzbbvnzeflsyzffikgnqpfyyoxgchrsosdomacmlfsmvztstrmprsukxchlxpgoiimcvueeysmrethmokudcwnoxdyxaojsyjhcorscllxbrdmqanyywdencqvrxrykwapneqbdevsxqnkxpshrwgvuctrbcvmmyyqjtdrnsyxojskbyboiqoaqsusmcanpjowfwdksedafofebqfhlrcmaoxictcxhhmgeueidjjvkxxdhvaaqwqkvrfknfvnvqseehddbtlwyhobibwonloliqiclvkxpvmvfiopxjwuwmdqtmgrqewefanwyutcjdzgrkgjowgpvwbvdcaarlobwgwjnwdrfajdmiajwxwzmfmjdgeeygzowlpmbyeedpaqathcmcggymlpjwmoxgttwyccpyttsybjnrdifgspavzqdjqxmnumlofzdhwqmmquymmxidfmigceboxnehkzlvpsbfopgxwqjkdzaibgimxicfrwfficnkskmzbazoaqkzyscsbvirtgisqdzopzhbtpnvrkweuwrlhilyohmgakvxooyipimkbncwfhiypmjhuqraoptmdtknqulhuqfahnawqqhxgrqqyqxiprjcbzphoqqnoydultlarooiopayhvjzzobjpcwkkarhshkvmspojljxpvybnkvabphvgcedlxmutprexubxubzsrwnjeuockmriewwskwwjrsjnxchcloutqzisltrjvohqckhsldvypwylhtejztdshjntmwvnygyxnnkrwqfoizszraevalfokmfimneyqwnpvtomyrecdvadthbxzcjdzdbinlzxwqdaomljbhlvxpzmelcjtxudcdwgvqsdumypzcujeqajsbutfmyrqzmhuelyaupuajrazsenjvqeoadfogwwfiykkoaxabhihtgcyxkfneejwdpxwrhygsmhtgwosheaizmngyikxaihfkzyqbvxqomkjpvejaqfmkbxqnirylwojablxrvarvuppooywbyheqvodvfhlyvvwdzkrkxlqjrkgnxqjrazxqqjycnjthwjdxarcipcfkcufzsfihtfirdxipfizkrukrcjfoiehpencmzkjxgerwervczxfozdhalwsrgpyjuzhcktrwjmlwwujqrqpryhbmvuekwniryylpjcibbdggiuhwbsopbqwbhapnkxyuezsrhxaagyuiyyvjyrgqpngzkrugfydbhekbbgfkhqantesdprcogqclthredomaikgvmizqfgsreizjlaycdhxkjzfoevcohckyhoyjprjjxzqvgbeabwdesacbwgawepspblxbxijihnnewnigrmkdtrpmqnufnkqpylxsxhlmnxptoiscfjezkbywluexexjeaeghftswkaxqtfvalzbsbhuldhfmhwjhvlxcwdelnrzxuhgtigyzxokknwwskblroubrvmuhzhomxqothcqqasccokuyfrvhbpunsmadljpuvtacosgbdfjwzmzsrnbyyzljzelaimgdjzsxmsvkdbswceueezblglqdvvkxtpcujmwrlnuikouguteneyubdozcirisnielfsfaaeeclkhmrcsiaignolqijovzuofzfwxknmunybiteudqwmcfmmraxmbgqnbrepsawlitmohassjctziwssussdgqekmomazkehuotdquywontmcqfdjytkobszshanaahybyztonzfsxagzgypfwrbvycsfhuwkpyiknzjbtjyswkyyqfbjgxrpdvftuvzazldeyvarqokrohakuiynmvhzlvpfcpmvtuswqpukaigiltiptdqwiwnkorwpwfavblhyxcayanqghpsxhtxxmomfusfxychdoipvhlkhyhquodgicvxpleclzdlpjnqrhzsqgywndrngzdhddlfrdfdkpxygsyivnkyllgdgjqmnjkqoaggyigupeszaaiwcaxpsmdlbncpbewgootnxflxkyjdtwfhlneoebtusajmpcunolyoljzvdwlblkufvgfwmfnujzlgibgekepizmkvrgaosdksjztgrggivjnjutjiupezyliytifpmcwlepaflxrvkmxmfykfzlcoyagtwaapsjsisfleewvcxhacdnoutiaswmrrowspudxfyirdrvzgoxwfddbjesttyiegorizayjtptmqjawdlvexavcqyxoyfofhlntiknsfhyyxowhydwliowfxvprmvdhhlswcaohxydptlhzqolghsumdfejejtxdxrsoxgdauujhqmoekvwngwykeisutbknmyrlwemprzylvwpfipcgxivtardnyeelkkoegcmmbbqxfwinjmemhmujzqsdwwvubnpklxfavwfucegnyfkjdhvdvfugrgmieiyqkvgmsxmndyagiileudwjmvkamrfiymbvxnbtxondjyezoxgzfgczkzqbhpzqljridyekktyfdxyjanxvbfxggbiyqiflxaffrhcgrnpeqsunhysnaqrgmkpfnvnjrahhiuqwwrmjpcfztnmlwtwrxuiwdsufrffqbweglkbiihkqtajmdxrckljolwvaqlsssldowrstawykzqycmvhbhxdehodxigehgwivduygijbcdxhhgmdcemedapvuclhbgddgecvehtbnhgktvwlpostvfrutwvnukuwqnmyyviipmzjvqkgxocvqipyrdbhhdwucfybxglygbecdiudnfbcfgzxuzvadjxiufpiyxfpcgnrskzoobfofqqkymtywnmaalypgvfthfbugmwaqihcgiypbvqqulafbftsgcxsffdblbcojgwqlihahqvlumlwhiclpkgnwoysxdmjontcxelxxtadafrtkqelplpstokagittwitvwagelqqkmjgwabtcidjizzzdqboagubirutfcrmiuydyduqbfbqzhnuqguwdkierojpoofjynxixxfpzrmmppiupzllrgynngccazhqmosjipseoibjcosxunwilqvehiciqchktcarjryoxtnyydejyedxwtktqmdehfygrurccdaromvcwpgwbmwrichzkembthbrvdzhnqddkvxhemljdkgciictkuhvtehmqugtskgpejfcpqneorqvssszwbqlukcmvngrvjfxcksjzgrxdihjdrpqkrhdiqiiiyrfztyyhejleoejnxndmozvtaicuhmzzceotkuivpfsalmrkawxyuexpnsdmtedzkvvuowoemdlodjhfbbmohaxezaiklecwpqakjgojgxsucnzgbdmqgeuaowqgqjuhbyzeeuhhuxihiwngtwlceemqchcfsmyxgaryybfmlmsultghnngalgvnslwogyeyxvqlaxoiphskxhtsozfqdvsblhgymfdfnwhuirdxsdqfhsdpxudeopgehsreklavccriotdkewclthbpccmrxycpcshxnrvrfzpwbobxkjyprgtpqjfacpyvtvwmtfltejbboxgjfqeldjqualijjfnkbrcqsydgifrarjqoomkfrjtnnlpcsioqynqbcgylmyhdzezctxgbohwuqoslysfsmwgnywsghhprdykxyhzcejzddhhfabsksyhovhusvlkyomxevrgkecpqizlptieorihsrhrhclpscxmitxzidfrxpdayqegibbfagzlwhnvsefzeadilrptxgumndxjejxvbqkymrjysxgejrocdwnufhbroxbnlsaeezlgejogqfdmwsqaqjzbpmcyppwodangvdtspwjxnniitwwojcxmhmzkvcydfelokrpthauxmdodlvfyeuqalcypoirtmojnkjhtofwcdmwlmejizqttmzrbmzilpissdrxuebstfpgbnfoilbizrsdrydoofyqcbqyeygctvblglqkfnouhgbbivzmwtioxcmoxlhxhdxbvwlyainlaryjhebvmlzzbguwtyplbmzqfkfpjvrsxjoaxgzolyvbyhgzaoxape

输出:
541435
一个样例输入输出

看到这个样例,输入到程序中抛出了异常  java.lang.StringIndexOutOfBoundsException: String index out of range: 6176

所以我们输入就不能使用String 来接收这个很长的字符串了,要想个别的办法才行。

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStreamReader;
 4 
 5 public class 完美的代价 {
 6      
 7     public static void main(String[] args) throws IOException{
 8         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
 9         int len = Integer.parseInt(reader.readLine());
10         char[] s = reader.readLine().toCharArray();
11         reader.close();
12         if (palindrome(s, 0, len - 1)) {
13             System.out.println(cnt);
14         } else {
15             System.out.println("Impossible");
16         }
17     }
18     
19     private static int cnt = 0;
20     private static boolean haveMiddle = false;
21     
22     private static boolean palindrome(char[] s, int a, int b) {
23         if (b <= a) {
24             return true;
25         }
26 
27                 // 从最后的位置开始遍历字符串
28         for (int i = b; i > a; i--) {
29             if (s[a] == s[i]) {
30                 exchangeTo(s, i, b);
31                 cnt += getExchangeTimes(i, b);
32                 return palindrome(s, a + 1, b - 1);
33             }
34         }
35 
36                 // 如果没有出现过中间字符
37         if (!haveMiddle) {
38             haveMiddle = true;
39             cnt += getExchangeTimes(a, s.length / 2);
40             return palindrome(s, a + 1, b);
41         }
42         return false;
43     }
44     
45     private static int getExchangeTimes(int a, int b) {
46         return b - a;
47     }
48     
49     private static void exchangeTo(char[] s, int a, int b) {
50         char temp = s[a];
51         for (int i = a; i < b; i++) {
52             s[i] = s[i + 1];
53         }
54         s[b] = temp;
55     }
56     
57 }
View Code2

 

 

 

 

posted @ 2020-03-21 10:45  AI未来10Y  阅读(468)  评论(0编辑  收藏  举报