File tree Expand file tree Collapse file tree 1 file changed +20
-21
lines changed
Expand file tree Collapse file tree 1 file changed +20
-21
lines changed Original file line number Diff line number Diff line change 11// https://leetcode.com/problems/valid-palindrome
22
3+ #include < string>
4+
35class Solution {
46public:
5- bool isPalindrome (string s) {
6- string str = " " ;
7- for (int i = 0 ; i < s.size (); i++) {
8- if (isalnum (s[i])) {
9- str += tolower (s[i]);
10- } else {
11- continue ;
12- }
13- }
14- string copy = str;
15- reverse (str.begin (), str.end ());
16- int i = 0 ;
17- int j = 0 ;
18- while (i < str.size () && j < copy.size ()) {
19- if (str[i] != copy[j]) {
20- return false ;
21- }
22- i++;
23- j++;
24- }
25- return true ;
7+ bool isPalindrome (std::string s) {
8+ std::string str;
9+ str.reserve (s.size ());
10+ for (size_t i = 0 ; i < s.size (); i++) {
11+ if (isalnum (s[i])) {
12+ str += std::tolower (static_cast <unsigned char >(s[i]));
13+ }
14+ }
15+ size_t left = 0 ;
16+ size_t right = str.size () - 1 ;
17+ while (left < right) {
18+ if (str[left] != str[right]) {
19+ return false ;
20+ }
21+ ++left;
22+ --right;
2623 }
24+ return true ;
25+ }
2726};
You can’t perform that action at this time.
0 commit comments