栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

ABC#237 C

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ABC#237 C

C

原题链接
题目大意:给定一个字符串str,判断能否通过在该字符串头部添加’a’,使该字符串变成回文串。

基本思路:将str头部和尾部的’a’去除,看剩下的字符串是否为回文串。若剩下的子串不是回文串,则结论为否。
需要特别注意的是:由于只能在字符串头部添加’a’,因此若str头部的’a’的个数比尾部的’a’的个数多,则结论也是否。

技巧:回文串的判断

bool isPalindrome(string str)
{
    string str2 = str;
    reverse(str.begin(), str.end());

    if (str == str2) return true;
    else return false;
}

代码1:双指针

#include 
#include 
using namespace std;

const int N = 1000010;
char s[N];

int main()
{
    cin >> s;
    bool flag = 1;
    int i = 0, j = strlen(s) - 1, cnt1 = 0, cnt2 = 0;
    while (s[i] == 'a') i ++, cnt1 ++;
    while (s[j] == 'a') j --, cnt2 ++;
    
    if (cnt1 > cnt2) flag = 0;
    
    while (i < j)
    {
        if (i >= j) break;
        else if (s[i] != s[j]) 
        {
            flag = 0;
            break;
        }
        else i ++, j --;
    }
    
    if (flag) cout << "Yes";
    else cout << "No";
    return 0;
}

代码2:string

#include 
#include 
using namespace std;

#define all(x) (x).begin(), (x).end()

int main()
{
    string str, str2;
    int cnt1 = 0, cnt2 = 0;
    cin >> str;
    while (str.size() && str.back() == 'a') str.pop_back(), cnt1 ++; // 去掉尾部的‘a’
    reverse(all(str));
    while (str.size() && str.back() == 'a') str.pop_back(), cnt2 ++; //去掉头部的‘a’

    str2 = str;
    reverse(all(str));

    if (str == str2 && cnt2 <= cnt1) cout << "Yes";
    else cout << "No";
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/723372.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号