【LeetCode】39. Valid Palindrome

题目描述(Easy)

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

题目链接

https://leetcode.com/problems/valid-palindrome/description/

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

算法分析

提交代码:

class Solution {
public:
	bool isPalindrome(string s) {
		if (s.empty()) return true;
        transform(s.begin(), s.end(), s.begin(), ::tolower);
		auto left = s.cbegin();
		auto right = prev(s.cend());
        
		while (left < right)
		{
            if(!isalnum(*left)) ++left;
            else if(!isalnum(*right)) --right;
            else if(*left != *right) return false;
            else { ++left, --right; }
		}

		return true;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, string str, bool expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	bool result = s.isPalindrome(str);

	if(result == expected)
		printf("passed\n");
	else
		printf("failed\n");
}

int main(int argc, char* argv[])
{
	
	Test("Test1", string("A man, a plan, a canal: Panama"), true);
	Test("Test2", string("race a car"), false);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82315144