Re: [閒聊] 每日leetcode

作者: enmeitiryous (enmeitiryous)   2024-08-24 21:07:24
564. Find the Closest Palindrome
題目:給你一個純數字字串n,求除了n本身外與他最相近的回文字串,如果有複數
字串距離相同則求最小的
思路:
和這個月的translate number to english很像,都是概念不難但很麻煩的hard
撇除1位數和20以下的特例外,對任一數字n而言只有3種候選答案:
1. 最直接的n長度切一半倒貼後面:7999->7997
2. n長度一半的位數+1再倒貼後面:7997->8008 99907->100001
3. n長度一半的位數-1在倒貼後面:7997->7887 100001->99999
所以就針對n列出這三種可能,並注意進位或少一位的可能列出求差最小即解,要注意
的是n的數字可以到10**18,所以轉變字串到數字用atoll
string nearestPalindromic(string n) {
string posb1="0";
string posb2="0";
string posb3="0";
string o_temp;
string m_temp;
if(n.size()==1){
if(n[0]-'0'==0){
return "1";
}
else{
return to_string(n[0]-'0'-1);
}
}
if(n.size()==2){
int yt=atoi(n.c_str());
if(yt<12){
return "9";
}
if(yt<17){
return "11";
}
if(yt<21){
return "22";
}
}
int te_len=n.size()/2;
long long int orig=atoll(n.c_str());
//cout<<"ter "<<n.substr(0,te_len)<<"\n";
stack<char> prod;
string temp_pal="";
for(int i=0;i<te_len;++i){
prod.push(n[i]);
}
while(!prod.empty()){
temp_pal+=prod.top();
prod.pop();
}
int pal=atoi(temp_pal.c_str());
///pal: if n=78995=>pal=87
//sev case:
//78987 78887 79097
//if n=7865 sev case:7887 7777 7997
if(n.size()&1){
posb1=n.substr(0,te_len+1)+temp_pal; //78987=>789
//now for +1 term: 79097
if(n[te_len]=='9'){
o_temp=to_string(atoi(n.substr(0,te_len+1).c_str())+1);
if(o_temp.size()==te_len+2){
//進位了:999->(100)1->telen=1 99997->(1000)01->telen=2
for(int k=te_len-1;k>=0;

Links booklink

Contact Us: admin [ a t ] ucptt.com