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;
}
測試結果:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章