溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

leetCode 125. Valid Palindrome 字符串

發(fā)布時(shí)間:2020-08-11 04:49:06 來(lái)源:網(wǎng)絡(luò) 閱讀:439 作者:313119992 欄目:編程語(yǔ)言

125. Valid Palindrome


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

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

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

題目大意:

回文的檢測(cè)。

思路:

1.清洗字符串,得到只有數(shù)字和字母的字符串。

2.通過(guò)比較首尾的字符來(lái)判斷。

代碼如下:

class Solution {
public:
    vector<string> stringSplit(string s, const char * split)
    {
    	vector<string> result;
    	const int sLen = s.length();
    	char *cs = new char[sLen + 1];
    	strcpy(cs, s.data());
    	char *p;
    
    	p = strtok(cs, split);
    	while (p)
    	{
    		printf("%s\n", p);
    		string tmp(p);
    		result.push_back(tmp);
    		p = strtok(NULL, split);
    	}
    	return result;
    }
    bool isPalindrome(string s) {
    	if (s.size() == 0 || s.size() == 1)
    		return true;
    	vector<string> vecStrs = stringSplit(s," ~!@#$%^&*().,:;-?\"'`");
    	s = "";
    	for (int i = 0; i < vecStrs.size(); i++)
    		s += vecStrs[i];
    	if (s.size() == 1 || s.size() == 0)
		    return true;
    	int i = 0;
    	for (; i < s.size() / 2; i++)
    	{
    		if (s[i] <= 57 ||  s[s.size() - i - 1] <= 57)
    		{
    			if (s[i] == s[s.size() - i - 1])
    			{
    				continue;
    			}
    			else
    			{
    				return false;
    			}
    		}
    		else if (s[i] == s[s.size() - i - 1] ||
    			s[i] - s[s.size() - i - 1] == 32 ||
    			s[s.size() - i - 1] - s[i] == 32)
    		{
    			continue;
    		}
    		else
    		{
    			return false;
    		}
    	}
    	return true;
    }
};


上面的做法效率低下,還有對(duì)API不熟悉。

下面是對(duì)上面的改進(jìn):

參考https://discuss.leetcode.com/topic/48376/12ms-c-clean-solution

代碼如下:

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

這里使用了isalnum()函數(shù)來(lái)判斷是否為文字?jǐn)?shù)字。

通過(guò)使用tolower()來(lái)統(tǒng)一字符的大小寫,都變?yōu)樾憽?/p>


2016-08-11 13:26:25

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI