4I.Applese 的回文串(C++)

版权声明:本文为博主原创,未经博主允许不得转载 https://blog.csdn.net/Sherry_Yue/article/details/87435464

Applese 的回文串(C++)

点击做题网站链接

题目描述
自从 Applese 学会了字符串之后,精通各种字符串算法,比如……判断一个字符串是不是回文串。
这样的题目未免让它觉得太无聊,于是它想到了一个新的问题。
如何判断一个字符串在任意位置(包括最前面和最后面)插入一个字符后能不能构成一个回文串?

输入描述:
仅一行,为一个由字母和数字组成的字符串 s。

输出描述:
如果在插入一个字符之后可以构成回文串,则输出"Yes", 否则输出"No"。

示例1
输入

applese

输出
No

示例2
输入

java

输出
Yes

备注:
s 1 0 5 |s|≤10^5

解题思路:

可以认为插入和删除是等价的操作。想到这一点,这题就会好做很多。
如果这个串本身就是回文串,答案一定是Yes。
否则我们只需要考虑串中对称的位置不相等的两个字符,分别尝试把它们删掉后判断一下是不是回文的就行了。

解题代码:

#include <iostream>
#include <string>
using namespace std;

int check(const string& s)
{
    int n = s.length();
    for(int i=0;i<n;++i)
        if( s[i] != s[n-1-i] )
            return i;
    return -1;//如果字符串本身就是回文串,返回-1
}
int main()
{
    ios::sync_with_stdio(0);
    string s;
    cin >> s;
    int ans = check(s);
    if( ans==-1 ) cout << "Yes";
    else
    {
        string tmp = s;
        string s1 = s.erase(ans,1);//删除下标为i的1个字符
        string s2 = tmp.erase(tmp.length()-1-ans,1);//删除下标为tmp.length()-1-ans的1个字符
        if( check(s1)==-1 || check(s2)==-1 )//如果s1或s2是回文串
            cout << "Yes" << endl;
        else
            cout << "No" << endl;
    }
}

笔记:

笔记参考https://www.cnblogs.com/ylwn817/articles/1967689.html
关于C++中string的erase函数:
三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str ("This is an example phrase.");
  string::iterator it;

  // 第(1)种用法
  str.erase (10,8);
  cout << str << endl;        // "This is an phrase."

  // 第(2)种用法
  it=str.begin()+9;
  str.erase (it);
  cout << str << endl;        // "This is a phrase."

  // 第(3)种用法
  str.erase (str.begin()+5, str.end()-7);
  cout << str << endl;        // "This phrase."
  return 0;
}

猜你喜欢

转载自blog.csdn.net/Sherry_Yue/article/details/87435464