[LeetCode]Valid Palindrome

本文介绍了一种使用C++来判断字符串是否为回文的有效方法。通过忽略大小写及非字母数字字符,该算法提高了判断准确性。文章提供了两种实现方案,一种是先转换字符串再检查,另一种是在遍历过程中直接进行比较。
class Solution {
public:
	bool isPalindrome(string s) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		TransmitString(s);
		for (int i = 0, j = s.size()-1; i <= j; ++i, --j)
		{
			if(s[i] != s[j])
				return false;
		}
		return true;
	}

	void TransmitString( string& str ) 
	{//note: do not let the string move too much
		int i, j;
		for (i = 0, j = 0; i < str.size(); ++i)
		{
			if(str[i] >= '0' && str[i] <= '9')
			{
				str[j++] = str[i];
			}
			else if (str[i] >= 'a' && str[i] <= 'z')
			{
				str[j++] = str[i];
			}
			else if (str[i] >= 'A' && str[i] <= 'Z')
			{
				str[j++] = str[i]-'A'+'a';
			}
		}
		str = str.substr(0, j);
	}


};

second time

class Solution {
public:
    bool isValidChar(char c)
    {
        if('a' <= c && c <= 'z') return true;
        if('A' <= c && c <= 'Z') return true;
        if('0' <= c && c <= '9') return true;
        return false;
    }
    char lowerCase(char c)
    {
        if('A' <= c && c <= 'Z') return c-'A'+'a';
        else return c;
    }
    bool isPalindrome(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int l = 0;
        int r = s.size()-1;
        while(l < s.size() && !isValidChar(s[l])) l++;
        while(r >= 0 && !isValidChar(s[r])) r--;
        
        while(l < r)
        {
            if(lowerCase(s[l]) == lowerCase(s[r]))
            {
                l++;
                while(l < s.size() && !isValidChar(s[l])) l++;
                r--;
                while(r >= 0 && !isValidChar(s[r])) r--;
            }
            else return false;
        }
        return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值