File tree Expand file tree Collapse file tree 1 file changed +20
-17
lines changed Expand file tree Collapse file tree 1 file changed +20
-17
lines changed Original file line number Diff line number Diff line change @@ -2,32 +2,35 @@ class Solution {
2
2
public:
3
3
bool isPalindrome (string s)
4
4
{
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)
7
9
{
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))
9
15
{
10
- // convert letters to lowercase
11
- s. at (i) = tolower (s. at (i)) ;
16
+ start++;
17
+ continue ;
12
18
}
13
- else
19
+ if (! isalnum (endChar))
14
20
{
15
- // remove non alpha-numeric char
16
- s.erase (s.begin () + i);
17
- i--;
21
+ end--;
22
+ continue ;
18
23
}
19
- }
20
24
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))
28
26
{
29
27
return false ;
30
28
}
29
+ else
30
+ {
31
+ start++;
32
+ end--;
33
+ }
31
34
}
32
35
33
36
return true ;
You can’t perform that action at this time.
0 commit comments