C++實(shí)現(xiàn)LeetCode(125.驗(yàn)證回文字符串)
[LeetCode] 125.Valid Palindrome 驗(yàn)證回文字符串
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.
驗(yàn)證回文字符串是比較常見的問題,所謂回文,就是一個(gè)正讀和反讀都一樣的字符串,比如“l(fā)evel”或者“noon”等等就是回文串。但是這里,加入了空格和非字母數(shù)字的字符,增加了些難度,但其實(shí)原理還是很簡單:只需要建立兩個(gè)指針,left和right, 分別從字符的開頭和結(jié)尾處開始遍歷整個(gè)字符串,如果遇到非字母數(shù)字的字符就跳過,繼續(xù)往下找,直到找到下一個(gè)字母數(shù)字或者結(jié)束遍歷,如果遇到大寫字母,就將其轉(zhuǎn)為小寫。等左右指針都找到字母數(shù)字時(shí),比較這兩個(gè)字符,若相等,則繼續(xù)比較下面兩個(gè)分別找到的字母數(shù)字,若不相等,直接返回false.
時(shí)間復(fù)雜度為O(n), 代碼如下:
解法一:
class Solution { public: bool isPalindrome(string s) { int left = 0, right = s.size() - 1 ; while (left < right) { if (!isAlphaNum(s[left])) ++left; else if (!isAlphaNum(s[right])) --right; else if ((s[left] + 32 - 'a') %32 != (s[right] + 32 - 'a') % 32) return false; else { ++left; --right; } } return true; } bool isAlphaNum(char &ch) { if (ch >= 'a' && ch <= 'z') return true; if (ch >= 'A' && ch <= 'Z') return true; if (ch >= '0' && ch <= '9') return true; return false; } };
我們也可以用系統(tǒng)自帶的判斷是否是數(shù)母字符的判斷函數(shù)isalnum,參見代碼如下;
解法二:
class Solution { public: bool isPalindrome(string s) { int left = 0, right = s.size() - 1 ; while (left < right) { if (!isalnum(s[left])) ++left; else if (!isalnum(s[right])) --right; else if ((s[left] + 32 - 'a') %32 != (s[right] + 32 - 'a') % 32) return false; else { ++left; --right; } } return true; } };
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(驗(yàn)證回文字符串)的文章就介紹到這了,更多相關(guān)C++驗(yàn)證回文字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
標(biāo)準(zhǔn)C++類string的Copy-On-Write技術(shù)
這里,我想從C++類或是設(shè)計(jì)模式的角度為各位揭開Copy-On-Write技術(shù)在string中實(shí)現(xiàn)的面紗,以供各位在用C++進(jìn)行類庫設(shè)計(jì)時(shí)做一點(diǎn)參考2013-11-11C++類與對象深入之引用與內(nèi)聯(lián)函數(shù)與auto關(guān)鍵字及for循環(huán)詳解
朋友們好,這篇播客我們繼續(xù)C++的初階學(xué)習(xí),現(xiàn)在對一些C++的入門知識做了些總結(jié),整理出來一篇博客供我們一起復(fù)習(xí)和學(xué)習(xí),如果文章中有理解不當(dāng)?shù)牡胤?還希望朋友們在評論區(qū)指出,我們相互學(xué)習(xí),共同進(jìn)步2022-06-06