Skip to content

Commit d4192aa

Browse files
authored
Update solution.cpp
Improved efficiency
1 parent 901e319 commit d4192aa

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

ValidPalindrome/solution.cpp

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,35 @@ class Solution {
22
public:
33
bool isPalindrome(string s)
44
{
5-
6-
for (int i=0; i<s.size(); i++)
5+
// Comparing front and back chars and increment closer to the middle
6+
int start = 0;
7+
int end = s.size() - 1;
8+
while (start <= end)
79
{
8-
if (isalnum(s.at(i)))
10+
char startChar = s.at(start);
11+
char endChar = s.at(end);
12+
13+
// Skip non alpha-numeric chars
14+
if (!isalnum(startChar))
915
{
10-
// convert letters to lowercase
11-
s.at(i) = tolower(s.at(i));
16+
start++;
17+
continue;
1218
}
13-
else
19+
if (!isalnum(endChar))
1420
{
15-
// remove non alpha-numeric char
16-
s.erase(s.begin() + i);
17-
i--;
21+
end--;
22+
continue;
1823
}
19-
}
2024

21-
// Comparing front and back chars and increment closer to the middle
22-
for (int i=0; i<s.size()/2; i++)
23-
{
24-
char front = *(s.begin()+i);
25-
char back = *(s.end()-1-i); // extra -1 to skip ending string null char
26-
27-
if (front != back)
25+
if (tolower(startChar) != tolower(endChar))
2826
{
2927
return false;
3028
}
29+
else
30+
{
31+
start++;
32+
end--;
33+
}
3134
}
3235

3336
return true;

0 commit comments

Comments
 (0)