头图

title: Daily Practice (40): Verifying Palindrome Strings

categories:[Swords offer]

tags:[Daily practice]

date: 2022/04/12


Daily practice (40): Verifying palindrome strings

Given a string, verify that it is a palindrome, considering only alphanumeric characters, ignoring case of letters.

Explanation: In this problem, we define the empty string as a valid palindrome.

Example 1:

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

output: true

Explanation: "amanaplanacanalpanama" is a palindrome

Example 2:

Input: "race a car"

output: false

Explanation: "raceacar" is not a palindrome

hint:

1 <= s.length <= 2 * 105

String s consists of ASCII characters

Source: LeetCode

Link: https://leetcode-cn.com/problems/valid-palindrome

Method 1: String preprocessing + double pointer

Thought analysis

isalnum: Determine whether the character variable c is a letter or a number, if so, return non-zero, otherwise return zero.

tolower: converts alphabetic characters to lowercase, non-alphabetic characters are not processed

1. First process the string s

2. Double pointer judgment, the left pointer points to the first position, the right pointer points to the last position, and judges whether they are the same in turn

 bool isPalindrome(string s) {
    string str;
    for (const char &ch : s) {
        if (isalnum(ch)) {
            str.push_back(tolower(ch));// 将数字和字母保存在 str 中,大写字母转换成小写
        }
    }
    // 左指针指向第一个位置,右指针指向最后一个位置
    // 依次比较是否相同
    int l = 0, r = str.size() - 1;
    while (l < r) {
        if (str[l] != str[r]) {
            return false;
        }
        l++;
        r--;
    }
    return true;
}

Method 2: Screening + Judgment

Thought analysis

Traverse the string s once, and keep the alphanumeric characters in another string sgood. In this way, we only need to judge whether sgood is a

An ordinary palindrome can be

Use the string reversal API in the language to get the reversed string sgood_rev of sgood

 bool isPalindrome(string s) {
    string sgood;
    for (const char &ch : s) {
        if (isalnum(ch)) {
            sgood.push_back(tolower(ch));// 将数字和字母保存在 sgood 中,大写字母转换成小写
        }
    }
    string sgood_rev(sgood.rbegin(), sgood.rend());// API逆转字符串
    return sgood == sgood_rev;
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记