前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >西安交通大学915-2019-编程2

西安交通大学915-2019-编程2

作者头像
lexingsen
发布2022-02-24 19:50:22
1340
发布2022-02-24 19:50:22
举报
文章被收录于专栏:乐行僧的博客乐行僧的博客

题目描述:

在这里插入图片描述
在这里插入图片描述

解题思路:

  • 包含空格,首先去除空格
  • 利用回文的定义,遍历一次

代码实现:

代码语言:javascript
复制
#include <iostream>
#include <stack>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
using namespace std;


bool RecursionSolution(const string &s, int i, int j) {
    if (i >= j) {
        return true;
    }
    if (s[i] != s[j]) {
        return false;
    }
    return s[i] == s[j] && RecursionSolution(s, i + 1, j - 1);
}

bool NoRecursionSolution(const string s) {
    int n = s.length();
    for (int i = 0; i < n / 2; i++) {
        if (s[i] != s[n - 1 - i]) {
            return false;
        }
    }
    return true;
}

void RemoveSpace(string &s) {
    string res = "";
    for (auto c: s) {
        if (c != ' ') {
            res += c;
        }
    }
    s = res;
    return;
}


void ToUpper(string &s) {
    // 统一转换为大写
    for (auto & c: s) {
        if (islower(c)) {
            c ^= 32;
        }
    }
}

void TestCase() {
    using psb = pair<string, bool>;
    vector<psb> t = {
        {"123321", true},
        {" 12 3 4 3 21", true},
        {"abcAbc", true},
        {"abcCbA", true},
        {"aaccbbdd", false}
    };

    bool flag = false;
    for (auto& x : t) {
        RemoveSpace(x.first);
        ToUpper(x.first);
        if (RecursionSolution(x.first, 0, x.first.length() - 1) != x.second || NoRecursionSolution(x.first) != x.second) {
            flag = true;
        }
    }
    if (flag) {
        cout << "error" << endl;
    } else {
        cout << "all accept" << endl;
    }
}



int main() {
    cout << "please input str:" << endl;
    string s;
    getline(cin, s);
    RemoveSpace(s);
    

    cout << s << endl;
    cout << "case 1 recursion solution" << endl;
    if (RecursionSolution(s, 0, s.length() - 1)) {
        cout << "yes" << endl;
    } else {
        cout << "no" << endl;
    }

    cout << "case 2 no recursion solution" << endl;
    if (NoRecursionSolution(s)) {
        cout << "yes" << endl;
    } else {
        cout << "no" << endl;
    }

    TestCase();
    return 0; 
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 解题思路:
  • 代码实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档