[Easy] 125. Valid Palindrome
发布日期:2021-05-07 18:21:23 浏览次数:23 分类:精选文章

本文共 1172 字,大约阅读时间需要 3 分钟。

  1. Valid Palindrome
  2. Given a string, determine if it is a palindrome by considering only alphanumeric characters and ignoring cases. Note that an empty string is considered a valid palindrome.

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

    Example 2: Input: "race a car" Output: false

    Solution Code:

    class Solution {
    bool isPalindrome(string s) {
    if (s.empty()) return true;
    int j = s.size() - 1;
    int i = 0;
    while (i < j) {
    if (!isalnum(s[j])) {
    j--;
    continue;
    }
    if (!isalnum(s[i])) {
    i++;
    continue;
    }
    if (tolower(s[i++]) != tolower(s[j--])) {
    return false;
    }
    }
    return true;
    }
    }

    This solution efficiently checks for palindromes by comparing characters from both ends of the string, ignoring non-alphanumeric characters and case differences. The algorithm runs in O(n) time complexity, where n is the length of the string, making it optimal for this problem.

    Note: The comparison is done in a case-insensitive manner to ensure uniformity in validation.

上一篇:[Easy] 136. Single Number
下一篇:[Easy] 122. Best Time to Buy and Sell Stock II

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年03月24日 17时51分19秒