【英文】验证回文串

Preface

LeetCode solution, language Java

Problem

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public boolean isPalindrome(String s) {

// Convert all characters to lowercase
s = s.toLowerCase();

// Remove non-lowercase letters and non-digits
String str = new String();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i)>=97 && s.charAt(i)<=122) {
str += s.charAt(i)+"";
} else if (s.charAt(i)>=48 && s.charAt(i)<=57) {
str += s.charAt(i)+"";
}
}

/*
Algorithm: Check if it is a palindrome
Create a flag, which is set to true by default, indicating it is a palindrome
If there is any non-palindrome condition in the loop, set the flag to false
After the loop, if no non-palindrome condition is found, the flag remains true (default)
*/
boolean flag = true;
for (int i = 0; i < str.length()/2; i++) {
if (!(str.charAt(i)+"").equals(str.charAt(str.length()-(1+i))+"")) {
flag = false;
}
}

return flag;
}

}

Completion