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.
题目大意:
回文的检测。
思路:
1.清洗字符串,得到只有数字和字母的字符串。
2.通过比较首尾的字符来判断。
代码如下:
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; } };
上面的做法效率低下,还有对API不熟悉。
下面是对上面的改进:
参考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()函数来判断是否为文字数字。
通过使用tolower()来统一字符的大小写,都变为小写。
2016-08-11 13:26:25
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网页名称:leetCode125.ValidPalindrome字符串-创新互联
标题来源:https://www.cdcxhl.com/article44/csghhe.html
成都网站建设公司_创新互联,为您提供自适应网站、动态网站、企业建站、网站收录、定制网站、企业网站制作
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联