前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >回文字符串判断以及最长回文字符串长度判断「建议收藏」

回文字符串判断以及最长回文字符串长度判断「建议收藏」

作者头像
全栈程序员站长
发布2022-09-06 11:44:31
发布2022-09-06 11:44:31
91700
代码可运行
举报
运行总次数:0
代码可运行

大家好,又见面了,我是你们的朋友全栈君。

回文字符串,就是正着反着读都一样的字符串。

1、回文字符串判断

假如这个字符串为奇数长度的回文字符串,则除了最中间的字符外,其左右的字符串两两相同。

假如这个字符串为偶数长度的回文字符串,则其左右完全对称。

代码如下:

代码语言:javascript
代码运行次数:0
复制
#include<iostream>
#include<string>
using namespace std;
bool palindrome(string str)//判断是否为回文字符
{
	int length = str.size();
	if (length <= 0) return false;
	if (length == 1) return true;
	int left = length / 2 - 1;
	int right = length - length / 2;
	while (left >= 0 && right < length)
	{
		if (str[left--] != str[right++])
		{
			return false;
		}
	}
	return true;
}
int main()
{
      string str;
      getline(cin,str);
      cout<<palindrome(str);
      return 0;
}

2、最长回文字符串长度判断

从第一个字符开始,分析以其为中心的奇数长度或者偶数长度的最长回文字符串。

代码如下:

代码语言:javascript
代码运行次数:0
复制
#include<iostream>
#include<string>
using namespace std;
int longestpalindrome(string str)
{
	int length = str.size();
	if (length <= 0) return 0;
	if (length == 1) return 1;
	int i, j;
	int max = 0;
	for ( i = 0; i < length; i++)//以i为中心
	{
		for (j = 0;(i-j>=0)&&(i+j<length);j++)//奇数回文字符串
		{
			if (str[i - j] != str[i + j])
				break;
		}
		if (2 * (j-1) + 1 > max)
			max = 2 * (j - 1) + 1;
		for (j = 0;(i-j>=0)&&(i+j+1<length);j++)//偶数回文字符串
		{
			if (str[i - j] != str[i + j + 1])
				break;
		}
		if (2 * j > max)
			max = 2 * j;
	}
	return max;
}
int main()
{
	string str;
	getline(cin, str);
	cout << longestpalindrome(str);
	return 0;
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/135131.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年6月5,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 回文字符串,就是正着反着读都一样的字符串。
    • 1、回文字符串判断
    • 2、最长回文字符串长度判断
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档