[LeetCode]125. Valid Palindrome

xiaoxiao2021-02-28  70

[LeetCode]125. Valid Palindrome

题目描述

思路

1.筛选去掉无用字符 2.判断当前字符串是否回文串

代码

#include <iostream> #include <string> using namespace std; class Solution { public: bool isPalindrome(string s) { /* int src = 0, cur = 0; while (src < s.size()) { if ((s[src] >= '0' && s[src] <= '9') || (s[src] >= 'a' && s[src] <= 'z') || (s[src] >= 'A' && s[src] <= 'Z')) { if (s[src] >= 'A' && s[src] <= 'Z') s[cur++] = s[src++] - ('A' - 'a'); else s[cur++] = s[src++]; } else ++src; } s.resize(cur); int start = 0, end = s.size(); while (start < end) { if (s[start] == s[end - 1]) { start++; end--; } else return false; } return true; */ for (int i = 0, j = s.size() - 1; i < j; i++, j--) { // Move 2 pointers from each end until they collide while (isalnum(s[i]) == false && i < j) i++; // Increment left pointer if not alphanumeric while (isalnum(s[j]) == false && i < j) j--; // Decrement right pointer if no alphanumeric if (toupper(s[i]) != toupper(s[j])) return false; // Exit and return error if not match } return true; } }; int main() { Solution s; cout << s.isPalindrome("race a car") << endl; system("pause"); return 0; }
转载请注明原文地址: https://www.6miu.com/read-63503.html

最新回复(0)