1. 程式人生 > >125驗證回文串

125驗證回文串

point uri case leetcode1 ans i++ 方案 etc 不一致

Algorithm

【leetcode】125驗證回文串

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

1)problem

給定一個字符串,驗證它是否是回文串,只考慮字母和數字字符,可以忽略字母的大小寫。

說明:本題中,我們將空字符串定義為有效的回文串。

示例 1:

輸入: "A man, a plan, a canal: Panama"
輸出: true
示例 2:

輸入: "race a car"
輸出: false

2)answer

1、普通思路

把數字和字符提取出來,然後如果是字母就轉換為小寫。加到新的字符串中。

對於這個新的字符串,使用一個多條件循環,分別從字符串頭、字符串尾遍歷字符串的中間值,如果不一致就退出。直到遍歷結束還是一致就判定為回文字符串。

2、高級思路

在discuss看到的答案。

用一個大循環分別從字符串頭、字符串尾遍歷字符串的中間值,裏面兩個小循環,用isalnum()函數判斷是不是字母數字,如果不是就向前移動指針。

https://leetcode.com/problems/valid-palindrome/discuss/119173/C++-Easy-to-Understand-Solution

3)solution

第一種方案:

先判斷是否為數字字母,跟之前寫的to-lower-case結合,把大寫轉換為小寫。

#include<stdio.h>
#include <string>
using std::string;

class Solution {
public:
    bool isPalindrome(string s) {

        string re_val = "";
        // 除去特殊符號,提取出字符串的小寫字母
        for (char str_val : s)
        {
            // 確認字母數字
            if (isalnum(str_val) != false)
            {
                if (str_val >= 'A'&& str_val <= 'Z')
                {
                    // 取小寫與大寫之間的差值,得到字符對應的小寫ASCII碼對應是什麽存進字符串中
                    re_val += (str_val + ('a' - 'A'));
                }
                else
                {
                    // 如果是小寫就不處理
                    re_val += str_val;
                }
            }
        }
        for (int i=0,j=re_val.size()-1; i<j;i++,j--) 
        {
            //一個指針從左邊指到右邊,一個指針從右邊指向左邊。如果有不同的值,就判斷不是回文字符。
            if (re_val[i] != re_val[j])
                return false;
        }
        return true;
    }
};


int main()
{

    Solution solu;
    bool ret;
    ret = solu.isPalindrome("A man, a plan, a canal: Panama");
    printf("%d \n", ret);
    ret = solu.isPalindrome("race a car");
    printf("%d \n", ret);
    return 0;
}

第二種方案:

bool isPalindrome(string s) {
    for (int i = 0, j = s.size() - 1; i < j; i++, j--) { // Move 2 pointers from each end until they collide
        while (isalnum(s[i]) == false && i < j) i++; // Increment left pointer if not alphanumeric
        while (isalnum(s[j]) == false && i < j) j--; // Decrement right pointer if no alphanumeric
        if (toupper(s[i]) != toupper(s[j])) return false; // Exit and return error if not match
    }
    
    return true;
}

125驗證回文串