二刷,用时3ms,内存9.81MB
一定要注意,是移除所有除了数字、字母以外的字符
class Solution { public: //'a' - 'A' = 32 bool isPalindrome(string s) { int left = 0,right = s.size()-1; while(left < right){ while(left < right && !(s[left] >= 'a' && s[left] <= 'z' || s[left] >= 'A' && s[left] <= 'Z' || s[left] >= '0' && s[left] <= '9')) ++left; while(left < right && !(s[right] >= 'a' && s[right] <= 'z' || s[right] >= 'A' && s[right] <= 'Z' || s[right] >= '0' && s[right] <= '9')) --right; if(((s[left] <= 'Z') ? s[left]+32 : s[left]) != ((s[right] <= 'Z') ? s[right]+32 : s[right])) return false; ++left;--right; } return true; } };
两年前一刷的代码。456ms,7.14MB
class Solution { public: bool isPalindrome(string s) { int sizes=s.size(); for(int i=0;i<sizes;i++){ if(!isalnum(s[i])){ //用于检查字符串是否只由字母和数字组成的函数 s.erase(s.begin()+i);i--;sizes--;continue; } if(isupper(s[i])){//用于检查字符是否大写字母 s[i] = s[i] + 32; } } if(sizes == 0) return true; for(int i=0;i<sizes/2;i++){ if(s[i]!=s[sizes-1-i]) return false; } return true; } };
标签:right,int,125,&&,回文,leetcode,left From: https://www.cnblogs.com/uacs2024/p/18603258