leetcode:字符串之Valid Palindrome && Palindrome Number

leetcode:字符串之Valid Palindrome


回文编程思想先判断给定字符串的首尾字符是否相等,若相等,则判断去掉首尾字符后的字符串是否为回文,若不相等,则该字符串不是回文


题目:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
”A man, a plan, a canal: Panama” is a palindrome.
”race a car” is not a palindrome.
    Note: Have you consider that the string might be empty? This is is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.

即:检测字符串是否为回文数。与数字回文不同的是,题目中给出的英文句子/短语包含空格及标点符号,因此需要在算法设计时加多一层判断。

C++实现

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;
bool isPalindrome(string s) 
{
     transform(s.begin(), s.end(), s.begin(), tolower);
	 if (s.empty())
         return true;
     auto left = s.begin(), right = prev(s.end());
     while (left < right) 
	 {
         if (!isalpha(*left))
			 left++;	 
         else if (!isalpha(*right))
			 right--;
         else if (*left == *right)
		 {
			 left++;
             right--;
		 }
		 else return false;
      }
     return true;
}
int main()
{
	string s="A man, a plan, a canal: Panama";
//	string s="race a car";
//	string s="";
	cout<<s<<endl;
	bool vp;
	vp=isPalindrome(s);
	if(vp)
		cout<<s<<"  :is a palindrome"<<endl;
	else
		cout<<s<<"  :is not a palindrome"<<endl;

	return 0;
}


测试结果



leetcode:Palindrome Number

题目:

Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem ”Reverse Integer”,
you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.

即:判断数字回文。解法是,不断地取第一位和最后一位(10 进制下)进行比较,相等则取第二位和倒数第
二位,直到完成比较或者中途找到了不一致的位。

c++实现:

#include <iostream>

using namespace std;
bool isPalindrome(int x)
{
    if (x < 0) 
		return false;
    int d = 1; // divisor
    while (x / d >= 10)
		d *= 10;
    while (x > 0) 
	{

        int q = x / d; // quotient
        int r = x % 10; // remainder
        if (q != r) 
			return false;
        x = x % d / 10;
        d /= 100;
	}
    return true;
}
int main()
{
	int x=1234321;
//	int x=1234567;
	bool pn;
	pn=isPalindrome(x);
	if(pn)
		cout<<x<<"  :is a palindrome"<<endl;
	else
		cout<<x<<"  :is not a palindrome"<<endl;

	return 0;
}
测试结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值