Skip to content

Commit 634559d

Browse files
author
XuhuaHuang
committed
Refactor palindrome leetcode solution
1 parent a129894 commit 634559d

File tree

1 file changed

+20
-21
lines changed

1 file changed

+20
-21
lines changed
Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
// https://leetcode.com/problems/valid-palindrome
22

3+
#include <string>
4+
35
class Solution {
46
public:
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
};

0 commit comments

Comments
 (0)